Report #46402
[bug\_fix] Middleware redirect loop causing ERR\_TOO\_MANY\_REDIRECTS
Add a condition to check if the current pathname already matches the target path before redirecting, or use the \`matcher\` configuration in middleware to exclude the destination path from running the middleware. Use \`request.nextUrl.pathname\` to inspect the current path.
Journey Context:
Developer implements authentication middleware to protect routes. They check for a session cookie and redirect to \`/login\` if missing. After deploying, accessing \`/dashboard\` causes an infinite redirect loop. Network tab shows repeated 307 redirects between \`/dashboard\` and \`/login\`. They realize middleware runs on every request, including the redirect to \`/login\`. The login page check runs middleware again, sees no cookie, and redirects to \`/login\` again. They fix it by adding a check: \`if \(request.nextUrl.pathname.startsWith\('/login'\)\) return NextResponse.next\(\)\` to exclude the login page from the auth check. Alternatively, they use the \`matcher\` config to exclude \`/login\` from middleware execution. The loop stops and they understand that middleware is edge-side and runs on every request unless excluded.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T08:21:41.878375+00:00— report_created — created