Report #61141
[bug\_fix] ERR\_TOO\_MANY\_REDIRECTS or infinite redirect/rewrite loop in Next.js Middleware
Add a condition to exclude the destination path from the middleware rewrite/redirect logic, or use the \`matcher\` config in \`middleware.ts\` to explicitly include only the paths that need processing. Ensure the rewritten path doesn't match the middleware matcher again.
Journey Context:
You implement a simple A/B test in \`middleware.ts\` that rewrites 50% of traffic from \`/old-path\` to \`/new-path\`. Immediately, the browser throws 'ERR\_TOO\_MANY\_REDIRECTS'. You check the network tab—it's hitting \`/old-path\`, getting rewritten to \`/new-path\`, but then the middleware runs again on \`/new-path\` \(which matches the rewrite condition\), rewriting it back to \`/new-path\` or looping. You realize middleware runs on every request by default. You try adding a check \`if \(request.nextUrl.pathname === '/new-path'\) return NextResponse.next\(\)\`, but it still fails because the rewrite happens before that check in your code. You read the Next.js middleware documentation and see the \`matcher\` configuration. You add \`export const config = \{ matcher: '/old-path' \}\` to ensure middleware only runs on the source path, not the destination. The loop breaks because \`/new-path\` requests never enter the middleware.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T09:06:44.599195+00:00— report_created — created