Repository navigation
Expand file tree
/
Copy pathmiddleware.ts
More file actions
36 lines (33 loc) · 1.58 KB
/
Copy pathmiddleware.ts
File metadata and controls
36 lines (33 loc) · 1.58 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
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
import { cspDirectives, cspReportOnly } from "./lib/securityHeaders";
// Convenience only: this redirects signed-out visitors before the page loads.
// It is NOT the security boundary — every Convex function re-checks identity and role.
const isProtectedRoute = createRouteMatcher(["/tools(.*)", "/my(.*)", "/admin(.*)"]);
export default clerkMiddleware(
async (auth, req) => {
if (!isProtectedRoute(req)) return;
const { userId } = await auth();
if (userId) return;
// Same-origin sign-in page (not Clerk's hosted portal), with a way back afterwards.
const signIn = new URL("/sign-in", req.url);
signIn.searchParams.set("redirect_url", req.nextUrl.pathname + req.nextUrl.search);
return NextResponse.redirect(signIn);
},
{
signInUrl: "/sign-in",
signUpUrl: "/sign-up",
// Per-request nonce + 'strict-dynamic' for scripts, on top of Clerk's defaults
// (lib/securityHeaders.ts). Clerk also sets the CSP on the request, so Next nonces its own
// inline scripts. CSP_REPORT_ONLY=1 reports instead of blocking (see SECURITY.md).
contentSecurityPolicy: { strict: true, directives: cspDirectives(), reportOnly: cspReportOnly() },
},
);
export const config = {
matcher: [
// Skip Next.js internals and static files, unless found in search params.
"/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
// Always run for API routes.
"/(api|trpc)(.*)",
],
};