import { NextRequest, NextResponse } from "next/server"; import { getToken } from "next-auth/jwt"; const publicPaths = [ "/login", "/signup", "/setup", "/api/auth", "/api/health", "/api/setup", "/api/onboarding", ]; const onboardingExemptPaths = [ "/onboarding", "/api/onboarding", "/api/auth", ]; function isPublic(pathname: string) { return publicPaths.some( (p) => pathname === p || pathname.startsWith(p + "/") ); } function isOnboardingExempt(pathname: string) { return onboardingExemptPaths.some( (p) => pathname === p || pathname.startsWith(p + "/") ); } export async function middleware(req: NextRequest) { const { pathname } = req.nextUrl; if ( pathname.startsWith("/_next") || pathname.startsWith("/favicon") || pathname.includes(".") ) { return NextResponse.next(); } if (isPublic(pathname)) { return NextResponse.next(); } const token = await getToken({ req, secret: process.env.AUTH_SECRET }); if (!token) { const loginUrl = new URL("/login", req.url); loginUrl.searchParams.set("callbackUrl", pathname); return NextResponse.redirect(loginUrl); } if ( token.onboardingComplete === false && token.orgRole === "owner" && !isOnboardingExempt(pathname) ) { return NextResponse.redirect(new URL("/onboarding", req.url)); } return NextResponse.next(); } export const config = { matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"], };