-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
50 lines (41 loc) · 1.38 KB
/
middleware.ts
File metadata and controls
50 lines (41 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'
import { NextResponse } from 'next/server'
const isPublicRoute = createRouteMatcher(['/sign-in(.*)', '/sign-up(.*)', '/welcome(.*)'])
export default clerkMiddleware(async (auth: any, request: any) => {
// Only block API routes accessed directly from browser
if (request.nextUrl.pathname.startsWith('/api')) {
const referer = request.headers.get('referer');
const isDirectAccess = !referer || !referer.includes(request.headers.get('host') || '');
if (isDirectAccess) {
return NextResponse.json({ error: 'Direct API access not allowed' }, { status: 403 });
}
}
if (!isPublicRoute(request)) {
await auth.protect()
}
(auth:any, req: any) => {
if (auth.userId && auth.isPublicRoute) {
let path = "/select-org"
if (auth.orgId) {
path = `/organizations/${auth.orgId}`
}
const orgSelection = new URL(path, req.url);
return NextResponse.redirect(orgSelection);
}
if (!auth.userId) {
return NextResponse.redirect("/sign-in");
}
}
});
export const config = {
matcher: [
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
'/api/:path*', // Explicitly match all API routes
],
publicRoutes: [
"/",
"/sign-in",
"/sign-up",
"/welcome"
],
}