From ca9fb13e466d26e55d6dcfbb1794c61c17ec5cb5 Mon Sep 17 00:00:00 2001 From: xiften <108333567+not-ani@users.noreply.github.com> Date: Mon, 14 Oct 2024 15:04:18 -0600 Subject: [PATCH] fix(nextjs): infinite redirect error --- apps/nextjs/src/middleware.ts | 40 +++++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/apps/nextjs/src/middleware.ts b/apps/nextjs/src/middleware.ts index fc33f92..ff626e7 100644 --- a/apps/nextjs/src/middleware.ts +++ b/apps/nextjs/src/middleware.ts @@ -4,31 +4,39 @@ import { auth } from "@amaxa/auth"; export default auth((req) => { const { nextUrl } = req; - const isLoggedIn = !!req.auth; - if ( - !isLoggedIn && - nextUrl.pathname !== "/sign-in" && - nextUrl.pathname !== "/unverified" && - !nextUrl.pathname.includes("/schedule") && - !nextUrl.pathname.includes("/apply") && - !nextUrl.pathname.includes("/api") - ) { - return NextResponse.redirect(new URL("/sign-in", nextUrl)); + // Define public routes that don't require authentication + const publicRoutes = ["/sign-in", "/unverified", "/schedule", "/apply"]; + + // Check if the current path is a public route + const isPublicRoute = publicRoutes.some((route) => + nextUrl.pathname.startsWith(route), + ); + + // Allow access to API routes without redirection + if (nextUrl.pathname.startsWith("/api")) { + return NextResponse.next(); } - const status = req.auth?.user.status; + // If not logged in and trying to access a protected route, redirect to sign-in + if (!isLoggedIn && !isPublicRoute) { + return NextResponse.redirect(new URL("/sign-in", nextUrl)); + } - if (status === "Unverified") { + if ( + isLoggedIn && + req.auth?.user.status === "Unverified" && + nextUrl.pathname !== "/unverified" && + nextUrl.pathname !== "/sign-out" + ) { return NextResponse.redirect(new URL("/unverified", nextUrl)); } + + return NextResponse.next(); }); // Read more: https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher export const config = { - matcher: [ - "/((?!api|_next/static|_next/image|favicon.ico).*)", - "/dashboard/:path", - ], + matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"], };