sQQuil
sQQuil

Reputation: 3

NextJS Infinite redirection loop when using middleware

I'm trying to make some routing logic using NextJS middleware. Based on this code: https://github.com/alexrusin/nextjs-cognito-auth/blob/5-reset-password-end/src/middleware.ts

When user is not authenticated (i'm using AWS Cognito) then they should be redirected to /auth/signup page, but if he is but don't have filled local profile i want to redirect him to /welcome page.

When I modify logic like this:

export async function middleware(request: NextRequest) {
    let response = NextResponse.next();
    const user = await authenticatedUser({request, response});

    try {
        await fetchAuthSession({forceRefresh: true});
    } catch (e) {
        throw e;
    }
    const account = await getAccount();
    const isInApp = /app|welcome/.test(request.nextUrl.pathname);

    if (isInApp) {
        if (!user)
            return NextResponse.redirect(new URL("/auth/login", request.nextUrl));
        if (user && account.statusCode === 404)
            return NextResponse.redirect(new URL("/welcome", request.nextUrl));
        return response;
    } else if (user) {
        return NextResponse.redirect(new URL("/app", request.nextUrl));
    }
}

export const config = {
    /*
     * Match all request paths except for the ones starting with
     */
    matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"],
};

My app makes infinite redirect loop to /welcome page. Please help

Solution or explanation why it's happened and how to fix it

Upvotes: 0

Views: 111

Answers (0)

Related Questions