feat: add sign-out redirect URL and enhance sign-in redirect handling

This commit is contained in:
Abhimanyu Saharan
2026-02-09 01:06:33 +05:30
parent f6bcd1ca5f
commit 5630f9b8e8
6 changed files with 123 additions and 6 deletions

View File

@@ -8,18 +8,40 @@ const isClerkEnabled = () =>
process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY,
);
// Public routes must include Clerk sign-in paths to avoid redirect loops.
const isPublicRoute = createRouteMatcher(["/sign-in(.*)"]);
// Public routes include home and sign-in paths to avoid redirect loops.
const isPublicRoute = createRouteMatcher(["/", "/sign-in(.*)", "/sign-up(.*)"]);
function isClerkInternalPath(pathname: string): boolean {
// Clerk may hit these paths for internal auth/session refresh flows.
return pathname.startsWith("/_clerk") || pathname.startsWith("/v1/");
}
function requestOrigin(req: Request): string {
const forwardedProto = req.headers.get("x-forwarded-proto");
const forwardedHost = req.headers.get("x-forwarded-host");
const host = forwardedHost ?? req.headers.get("host");
const proto = forwardedProto ?? "http";
if (host) return `${proto}://${host}`;
return new URL(req.url).origin;
}
function returnBackUrlFor(req: Request): string {
const { pathname, search, hash } = new URL(req.url);
return `${requestOrigin(req)}${pathname}${search}${hash}`;
}
export default isClerkEnabled()
? clerkMiddleware(async (auth, req) => {
if (isClerkInternalPath(new URL(req.url).pathname)) {
return NextResponse.next();
}
if (isPublicRoute(req)) return NextResponse.next();
// In middleware, `auth()` resolves to a session/auth context (Promise in current typings).
// Use redirectToSignIn() (instead of protect()) for unauthenticated requests.
const { userId, redirectToSignIn } = await auth();
if (!userId) {
return redirectToSignIn({ returnBackUrl: req.url });
return redirectToSignIn({ returnBackUrl: returnBackUrlFor(req) });
}
return NextResponse.next();
@@ -28,7 +50,7 @@ export default isClerkEnabled()
export const config = {
matcher: [
"/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
"/((?!_next|_clerk|v1|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
"/(api|trpc)(.*)",
],
};