I have a middleware in Next.js:
export async function middleware(request: NextRequest) {
const isUserLoggedIn = ...
if (isUserLoggedIn) {
return NextResponse.redirect(new URL('/user', request.url));
}
return NextResponse.next();
}
Basically, if user is logged in redirect to private route of the app (this is just a simple example).
The problem is that when redirecting, the middleware get called again in the new page and redirects again and so forth (infinite loop).
I tried using rewrite
instead of redirect
but the url is not changing and generally I don’t think this case requires this method.
Someone encountered this behaviour before? Can someone suggest a safe solution?