Report #49517
[bug\_fix] Next.js Middleware infinite redirect loop \(ERR\_TOO\_MANY\_REDIRECTS\)
Add an exclusion condition to prevent the middleware from re-processing the rewritten/redirected request \(e.g., check for a specific query parameter, cookie, or header that marks the request as already processed\), or use the matcher config in middleware.ts to exclude the destination path. Root cause: Middleware runs on every incoming request including the ones it just created via rewrite/redirect, causing a recursive loop.
Journey Context:
Developer creates middleware.ts to redirect users from /old-site/\* to /new-site/\*. Writes logic: if \(request.nextUrl.pathname.startsWith\('/old-site'\)\) \{ return NextResponse.redirect\(new URL\('/new-site' \+ rest, request.url\)\) \}. Deploys. Visits /old-site/page. Browser shows ERR\_TOO\_MANY\_REDIRECTS. Network tab shows 307 redirects bouncing between /old-site and /new-site. Developer realizes that after redirecting to /new-site, the browser requests that URL, but the middleware runs again on that request. If the logic accidentally matches /new-site \(or if there's a cookie check that fails again\), it redirects back. Developer fixes by adding a check: if request.nextUrl.pathname === '/new-site' return NextResponse.next\(\), or better, uses the matcher export in middleware.config to only run on /old-site/:path\*. Alternatively, sets a 'redirected=true' cookie and checks for it to break the loop. Loop stops, redirect works once.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T13:35:35.073341+00:00— report_created — created