Next.js Middleware Rewrites Into Its Own Matcher and Creates an Infinite Redirect Loop
/login keeps reloading and the browser console shows too many redirects; the same path is matched by middleware again after the rewrite or redirect.
What is actually looping
Next.js middleware runs before route matching and before the page, API route, or app route handler is selected. That means middleware can observe and change the request before the rest of the app sees it.
The loop appears when middleware sends the request to a path that also matches the same middleware. A rewrite is especially easy to miss because the browser URL does not change. The server receives the rewritten request, evaluates middleware again, and repeats the same decision.
A redirect has the same failure mode if the redirect target matches the same middleware pattern. The browser follows the Location header, requests the target path, and gets redirected again.
The core problem is not Next.js routing itself. The problem is that middleware is evaluated on the rewritten or redirected path too, and the matcher still applies.
How middleware matching works
Middleware lives in middleware.ts at the project root, or src/middleware.ts if src is used. The file exports a middleware function and usually a config.matcher value.
A matcher decides which incoming requests invoke middleware. In Next.js 14.x, matcher entries can be strings or regular-expression-like patterns supported by the routing layer. A common configuration is:
tsimport type { NextRequest } from 'next/server' import { NextResponse } from 'next/server' export function middleware(request: NextRequest) { return NextResponse.next() } export const config = { matcher: ['/dashboard/:path*'], }
That means every request under /dashboard runs through the middleware. If middleware rewrites /dashboard to /dashboard/login, the rewritten path still matches /dashboard/:path*.
Next.js evaluates middleware before the destination route is resolved. For a rewrite, the internal request path changes while the browser URL can stay the same. For a redirect, the browser makes a new request. In both cases, the matcher sees the target path again.
Why a rewrite can recurse
A rewrite changes the request that the app serves without changing the URL shown in the browser. That makes it useful for auth gates, regional routing, and A/B tests.
The problem comes when the rewrite target is inside the same protected namespace.
Consider this middleware:
tsimport { NextRequest, NextResponse } from 'next/server' export function middleware(request: NextRequest) { const isAuthed = request.cookies.get('session')?.value === 'valid' if (!isAuthed) { return NextResponse.rewrite(new URL('/dashboard/login', request.url)) } return NextResponse.next() } export const config = { matcher: ['/dashboard/:path*'], }
A request to /dashboard/settings matches the middleware. If the session is missing, the middleware rewrites to /dashboard/login.
That rewritten request also matches /dashboard/:path*. Middleware runs again. If the session is still missing, it rewrites to /dashboard/login again. The server keeps applying the same rule to the same path.
If the page at /dashboard/login also uses the same middleware, the response never reaches the page handler.
Redirects behave the same way:
tsimport { NextRequest, NextResponse } from 'next/server' export function middleware(request: NextRequest) { const isAuthed = request.cookies.get('session')?.value === 'valid' if (!isAuthed) { return NextResponse.redirect(new URL('/dashboard/login', request.url)) } return NextResponse.next() } export const config = { matcher: ['/dashboard/:path*'], }
The browser requests /dashboard/login, middleware runs again, and the browser keeps following the new Location response.
Confirming the loop from the request path
The key diagnostic is the path seen by middleware. A rewrite updates the internal request URL that middleware receives on the next pass. If the target path still falls under the same matcher, the loop is self-sustaining.
A minimal debugging helper can show the current pathname:
tsimport { NextRequest, NextResponse } from 'next/server' export function middleware(request: NextRequest) { console.log('middleware pathname:', request.nextUrl.pathname) return NextResponse.next() } export const config = { matcher: ['/dashboard/:path*'], }
If a request to /dashboard/settings is rewritten to /dashboard/login, the log will show both paths on successive middleware passes.
This is why the fix must change matching behavior or add a guard. Changing only the destination route does not stop recursion if the destination still matches.
Fix 1: exclude the public target from the matcher
The most direct fix is to prevent middleware from running on the login page or any other public fallback that is used by the rewrite or redirect.
Use a matcher that excludes the public route:
tsimport type { NextRequest } from 'next/server' import { NextResponse } from 'next/server' export function middleware(request: NextRequest) { const isAuthed = request.cookies.get('session')?.value === 'valid' if (!isAuthed) { return NextResponse.rewrite(new URL('/dashboard/login', request.url)) } return NextResponse.next() } export const config = { matcher: ['/dashboard/:path*', '/((?!dashboard/login).*)'], }
That pattern is broad, and broad patterns are easy to misread. A cleaner approach is to separate protected and public areas with explicit matchers if possible.
For example, if only private dashboard pages should use middleware, keep the matcher on private paths and move the login page outside that scope:
tsimport type { NextRequest } from 'next/server' import { NextResponse } from 'next/server' export function middleware(request: NextRequest) { const isAuthed = request.cookies.get('session')?.value === 'valid' if (!isAuthed) { return NextResponse.rewrite(new URL('/login', request.url)) } return NextResponse.next() } export const config = { matcher: ['/dashboard/:path*'], }
This is usually the best option because it removes the target route from the middleware scope entirely.
Fix 2: add a path guard inside middleware
If the destination must stay under the same URL prefix, you need an explicit guard that stops middleware from rewriting requests that are already on the public target.
tsimport { NextRequest, NextResponse } from 'next/server' const PUBLIC_PATHS = new Set(['/dashboard/login', '/dashboard/reset-password']) export function middleware(request: NextRequest) { const { pathname } = request.nextUrl if (PUBLIC_PATHS.has(pathname)) { return NextResponse.next() } const isAuthed = request.cookies.get('session')?.value === 'valid' if (!isAuthed) { return NextResponse.rewrite(new URL('/dashboard/login', request.url)) } return NextResponse.next() } export const config = { matcher: ['/dashboard/:path*'], }
This works because middleware now makes a different decision for the public route. The rewritten request reaches /dashboard/login, but the guard returns NextResponse.next() instead of rewriting again.
This guard should be matched to the exact path that middleware rewrites to. If the destination can vary, include every destination path in the guard. Otherwise the loop can still appear on a path that was forgotten.
Fix 3: use a cookie or header to mark an internal reroute
A guard based only on pathname is enough when the login page is static and public. If the rewrite is conditional and the target path stays inside the protected namespace, a marker can help prevent repeated rewrites during the same request chain.
tsimport { NextRequest, NextResponse } from 'next/server' export function middleware(request: NextRequest) { const isAuthed = request.cookies.get('session')?.value === 'valid' const alreadyRerouted = request.headers.get('x-auth-rerouted') === '1' if (!isAuthed && !alreadyRerouted) { const headers = new Headers(request.headers) headers.set('x-auth-rerouted', '1') return NextResponse.rewrite(new URL('/dashboard/login', request.url), { request: { headers, }, }) } return NextResponse.next() } export const config = { matcher: ['/dashboard/:path*'], }
This is more specialized and usually less desirable than a matcher exclusion. It can be useful when an internal path must remain within the same namespace and pathname-based exclusion is not enough.
Headers are only a tool for the current request chain. They do not replace a correct matcher. If the public route should never be protected, excluding it from the matcher is still simpler and safer.
Why NextResponse.next() on the public route is not optional
A common mistake is to assume that middleware only needs to check authentication once. In Next.js, middleware can be invoked repeatedly as the request is transformed or reissued.
If the request path after rewrite or redirect still belongs to the middleware scope, the middleware function must explicitly allow it through. Otherwise the logic that sends unauthenticated users to a fallback page becomes the same logic that blocks the fallback page.
This is why the loop is not a bug in rewrite() itself. It is a scope mismatch between the matcher and the destination path.
A safe pattern for protected routes
A reliable setup keeps public pages outside the protected matcher and only gates the private section.
tsimport type { NextRequest } from 'next/server' import { NextResponse } from 'next/server' export function middleware(request: NextRequest) { const session = request.cookies.get('session')?.value if (!session) { return NextResponse.redirect(new URL('/login', request.url)) } return NextResponse.next() } export const config = { matcher: ['/dashboard/:path*', '/account/:path*'], }
Here /login is not matched, so it cannot loop back into the same middleware. The protected paths remain protected, and the login page remains reachable.
If the login page itself needs middleware for another concern, use a second middleware condition or a separate matcher that does not overlap with the auth gate.
Verifying the fix
Use next dev or next start and test the exact path that used to loop. A redirect loop usually shows up in the browser as ERR_TOO_MANY_REDIRECTS. A rewrite loop may appear as repeated reloads, repeated server logs, or the same page never finishing navigation.
A simple browser test is enough:
bashcurl -I http://localhost:3000/dashboard/settings
For a redirect, inspect the Location header and ensure it points to a route outside the matcher. For a rewrite, the response status may still be 200, so inspect the rendered route and the middleware logs.
If you are using next.config.js redirects as well, check those too. A middleware redirect plus a config redirect can bounce through the same path even if each rule seems correct in isolation.
Keep the loop from returning
Prefer a matcher exclusion over an in-function guard when the public route can be moved outside the protected area. That makes the rule easier to reason about, and it prevents middleware from running at all on the fallback page.
Use a path guard when the fallback must stay in the same namespace or when the matcher needs to remain broad. In both cases, the destination route must be excluded from the recursion path.
The practical fix is to ensure that any rewrite or redirect target does not match the same middleware without an escape condition. If the target must match, add an explicit pathname guard. If it does not need middleware, keep it out of the matcher.