Question

Next.js middleware redirects in a loop after adding auth

Solved · 247 views · asked by yuki_builds · edited

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

ERR_TOO_MANY_REDIRECTS
What I’ve tried

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

Comment

1 answer

Marked as helpful by the asker
jonas_k · edited

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