Report #50668
[bug\_fix] ERR\_TOO\_MANY\_REDIRECTS or infinite redirect loop when using Next.js Middleware for authentication
Add a matcher configuration in middleware.ts to exclude the redirect destination path \(e.g., /login\) and static assets, or add an early return if request.nextUrl.pathname matches the destination.
Journey Context:
Developer implements authentication middleware in middleware.ts at the project root to protect routes. They check for a session cookie and if missing, return NextResponse.redirect\(new URL\('/login', request.url\)\). After deploying to Vercel or running next start, accessing any protected route results in the browser showing ERR\_TOO\_MANY\_REDIRECTS. Developer checks the Network tab and sees a rapid chain of 307 redirect responses bouncing between the original URL and /login. They realize that when the middleware redirects to /login, the browser requests /login, but the middleware runs again on that request, sees no session cookie, and redirects to /login again, creating an infinite loop. They examine Next.js middleware documentation and understand that middleware runs on every request unless configured with a matcher. They add a matcher configuration to the middleware export: export const config = \{ matcher: \['/\(\(?\!api\|\_next/static\|\_next/image\|favicon.ico\|login\).\*\)'\] \} to exclude the login path and static assets. Alternatively, they add an early return: if \(request.nextUrl.pathname === '/login'\) return NextResponse.next\(\). The redirect loop stops because the middleware no longer intercepts and redirects the destination route itself.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T15:31:45.935563+00:00— report_created — created