Report #31540
[bug\_fix] Next.js Middleware redirect loop or incorrect matcher
Add a condition to exclude the destination path from the redirect logic, or use the \`matcher\` export in \`middleware.ts\` to restrict which paths the middleware runs on. Root cause: Middleware runs on every path by default \(excluding static files unless configured\). If logic redirects to \`/login\` and the middleware runs on \`/login\` without excluding it, it redirects \`/login\` to \`/login\`, causing an infinite loop.
Journey Context:
Developer implements authentication middleware in \`middleware.ts\` to protect \`/dashboard\`. They write: \`export function middleware\(req\) \{ const token = req.cookies.get\('token'\); if \(\!token\) return NextResponse.redirect\(new URL\('/login', req.url\)\); return NextResponse.next\(\); \}\`. They visit \`/dashboard\` without a token. The browser shows \`ERR\_TOO\_MANY\_REDIRECTS\`. Checking the Network tab, they see 307 redirects cycling between \`/dashboard\` and \`/login\`. Realizing the middleware runs on \`/login\` too \(because it's in the root\), it redirects \`/login\` to \`/login\` infinitely. They fix it by adding: \`if \(req.nextUrl.pathname.startsWith\('/login'\)\) return NextResponse.next\(\);\` or by exporting a \`config\` object with \`matcher: \['/dashboard/:path\*'\]\` to ensure middleware only executes on protected routes, not on \`/login\` or static assets.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T07:19:31.989045+00:00— report_created — created