Report #55648
[bug\_fix] Next.js Middleware causing infinite redirect loop
Add a condition to check if the rewrite/redirect has already been applied \(e.g., check the pathname\), or use the \`matcher\` config in \`middleware.ts\` to explicitly exclude the destination path from being matched again.
Journey Context:
Developer writes \`middleware.ts\` to redirect unauthenticated users to \`/login\`. Checks \`if \(\!token\) return NextResponse.redirect\(new URL\('/login', request.url\)\)\`. Deploys. Browser shows 'ERR\_TOO\_MANY\_REDIRECTS'. Developer realizes the middleware is also running on the \`/login\` route, redirecting to \`/login\` again. Tries to add \`if \(request.nextUrl.pathname === '/login'\) return NextResponse.next\(\)\` but still fails due to trailing slashes or locale prefixes. Consults Next.js docs. Learns to use the \`matcher\` array in the middleware config to explicitly match only protected routes, excluding \`/login\` and static files. Alternatively, adds a check for a custom header. The infinite loop stops.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T23:54:05.664147+00:00— report_created — created