# 错误：超出最大调用堆栈大小 / 在路径 '/login' 的中间件中检测到重定向循环

- **ID:** `nextjs/middleware-redirect-loop-internal`
- **领域:** nextjs
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 92%

## 根因

中间件将请求重定向到相同路径（例如，将 /login 重定向到 /login）或重定向到另一个触发回环的路径，创建无限循环，耗尽调用堆栈。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Next.js 13.0.0 | active | — | — |
| Next.js 14.0.0 | active | — | — |
| Next.js 14.2.0 | active | — | — |

## 解决方案

1. ```
   添加条件，如果用户已经在目标路径上，则跳过重定向。示例：在 middleware.ts 中，在重定向逻辑之前检查 `if (request.nextUrl.pathname === '/login') { return NextResponse.next(); }`。
   ```
2. ```
   确保重定向目标是不同的路径。例如，保护 /dashboard 时，将未认证用户重定向到 /login，同时确保 /login 不会在未认证时重定向回 /dashboard。
   ```
3. ```
   仅在验证用户未认证且当前路径不是 /login 后使用 `return NextResponse.redirect(new URL('/login', request.url))`。示例：`if (!isAuthenticated && request.nextUrl.pathname !== '/login') { return NextResponse.redirect(...) }`。
   ```

## 无效尝试

- **** — The check does not prevent the redirect; it still redirects to the same path, causing an infinite loop. (100% 失败率)
- **** — If the user is already on /login, the redirect will point back to /login, creating a loop. (90% 失败率)
- **** — 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% 失败率)
