1

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.