import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server"; import { NextResponse } from "next/server"; const isProtectedRoute = createRouteMatcher(["/chat(.*)", "/api(.*)"]); /** * Middleware that keeps the landing page (/) public but protects /chat and /api. * If the user is not authenticated, redirect to the embedded /sign-in route, * passing a redirect_url param so that after sign-in they return to the * originally requested URL. */ export default clerkMiddleware(async (auth, req) => { const { userId } = await auth(); if (isProtectedRoute(req) && !userId) { const signInUrl = new URL("/sign-in", req.url); signInUrl.searchParams.set("redirect_url", req.url); return NextResponse.redirect(signInUrl); } 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)(.*)", ], };