Question

Next.js middleware redirects in a loop after adding auth

Solved · 98 viewsasked by yuki_builds

Added a middleware that sends signed-out users to /login. Now /login redirects to /login forever.

The dev server log after opening any page:

and the browser gives up with ERR_TOO_MANY_REDIRECTS.

What I’ve tried

Excluded /login in an if-statement, but the matcher still runs on it, I think.

Comment

2 answers

Marked as helpful by the asker
jonas_k

The matcher decides where the middleware runs, your if decides what it does. Exclude public paths in both, and always exclude static files:

export const config = { matcher: ["/((?!_next/static|_next/image|favicon.ico|login|auth).*)"] };

Also return NextResponse.next() explicitly on the public branch. A missing return in middleware is a silent redirect to nowhere.

Comment
Matcher plus the explicit return. /login loads now, and the logo came back too, it was being redirected as well. yuki_builds
kofi_mensah

Since the tags say Supabase: also exclude your auth callback route (/auth/callback or /auth/confirm) from the redirect. The user arrives there before the session cookie exists, so the middleware sees "signed out" and bounces them to /login mid-login.

And make sure the middleware refreshes the session (the updateSession helper from the Supabase SSR docs) before it decides. Otherwise an expired access token looks like a signed-out user and you get random redirects an hour after login.

Comment
The callback one would have been my next question. Excluded it. yuki_builds