import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server"; import { NextResponse } from "next/server"; // Routes that anyone can access (no auth required) const isPublicRoute = createRouteMatcher([ "/", "/sign-in(.*)", "/sign-up(.*)", "/sso-callback(.*)", "/api/webhooks(.*)", "/privacy(.*)", "/terms(.*)", "/pricing(.*)", "/invite(.*)", "/sign(.*)", ]); // Routes that should only be accessed when NOT authenticated // (authenticated users get redirected away from these) const isAuthOnlyRoute = createRouteMatcher([ "/sign-in(.*)", "/sign-up(.*)", ]); export default clerkMiddleware(async (auth, req) => { const { userId } = await auth(); const { pathname } = req.nextUrl; // If user is authenticated and trying to access sign-in/sign-up, redirect to home if (userId && isAuthOnlyRoute(req)) { return NextResponse.redirect(new URL("/home", req.url)); } // If user is NOT authenticated and trying to access a protected route, redirect to sign-up if (!userId && !isPublicRoute(req)) { return NextResponse.redirect(new URL("/sign-up", req.url)); } // If user is authenticated and trying to access the landing page, redirect to home if (userId && pathname === "/") { return NextResponse.redirect(new URL("/home", req.url)); } // Redirect old /dashboard URLs to /home if (pathname === "/dashboard") { return NextResponse.redirect(new URL("/home", req.url)); } // Allow the request to continue return NextResponse.next(); }); export const config = { matcher: [ // Skip Next.js internals and all 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)(.*)", ], };