# Error: Maximum call stack size exceeded / redirect loop detected in middleware for path '/login'

- **ID:** `nextjs/middleware-redirect-loop-internal`
- **Domain:** nextjs
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 92%

## Root Cause

Middleware redirects a request to the same path (e.g., redirecting /login to /login) or to a path that triggers another redirect back, creating an infinite loop that exhausts the call stack.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| Next.js 13.0.0 | active | — | — |
| Next.js 14.0.0 | active | — | — |
| Next.js 14.2.0 | active | — | — |

## Workarounds

1. **Add a condition to skip the redirect if the user is already on the target path. Example: In middleware.ts, check `if (request.nextUrl.pathname === '/login') { return NextResponse.next(); }` before the redirect logic.** (95% success)
   ```
   Add a condition to skip the redirect if the user is already on the target path. Example: In middleware.ts, check `if (request.nextUrl.pathname === '/login') { return NextResponse.next(); }` before the redirect logic.
   ```
2. **Ensure the redirect target is a different path. For example, if protecting /dashboard, redirect unauthenticated users to /login, but also ensure /login does not redirect back to /dashboard unless authenticated.** (90% success)
   ```
   Ensure the redirect target is a different path. For example, if protecting /dashboard, redirect unauthenticated users to /login, but also ensure /login does not redirect back to /dashboard unless authenticated.
   ```
3. **Use `return NextResponse.redirect(new URL('/login', request.url))` only after verifying the user is not authenticated and the current path is not /login. Example: `if (!isAuthenticated && request.nextUrl.pathname !== '/login') { return NextResponse.redirect(...) }`.** (95% success)
   ```
   Use `return NextResponse.redirect(new URL('/login', request.url))` only after verifying the user is not authenticated and the current path is not /login. Example: `if (!isAuthenticated && request.nextUrl.pathname !== '/login') { return NextResponse.redirect(...) }`.
   ```

## Dead Ends

- **** — The check does not prevent the redirect; it still redirects to the same path, causing an infinite loop. (100% fail)
- **** — If the user is already on /login, the redirect will point back to /login, creating a loop. (90% fail)
- **** — While this prevents infinite loops, it does not fix the root cause; the middleware still performs unnecessary redirects, and the user may end up on an unintended page. (70% fail)
