Skip to content

Commit

Permalink
fix(nextjs): infinite redirect error
Browse files Browse the repository at this point in the history
  • Loading branch information
not-ani committed Oct 14, 2024
1 parent 2ea041e commit ca9fb13
Showing 1 changed file with 24 additions and 16 deletions.
40 changes: 24 additions & 16 deletions apps/nextjs/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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).*)"],
};

0 comments on commit ca9fb13

Please sign in to comment.