错误:超出最大调用堆栈大小 / 在路径 '/login' 的中间件中检测到重定向循环
Error: Maximum call stack size exceeded / redirect loop detected in middleware for path '/login'
ID: nextjs/middleware-redirect-loop-internal
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Next.js 13.0.0 | active | — | — | — |
| Next.js 14.0.0 | active | — | — | — |
| Next.js 14.2.0 | active | — | — | — |
根因分析
中间件将请求重定向到相同路径(例如,将 /login 重定向到 /login)或重定向到另一个触发回环的路径,创建无限循环,耗尽调用堆栈。
English
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.
官方文档
https://nextjs.org/docs/app/building-your-application/routing/middleware#avoiding-redirect-loops解决方案
-
添加条件,如果用户已经在目标路径上,则跳过重定向。示例:在 middleware.ts 中,在重定向逻辑之前检查 `if (request.nextUrl.pathname === '/login') { return NextResponse.next(); }`。 -
确保重定向目标是不同的路径。例如,保护 /dashboard 时,将未认证用户重定向到 /login,同时确保 /login 不会在未认证时重定向回 /dashboard。
-
仅在验证用户未认证且当前路径不是 /login 后使用 `return NextResponse.redirect(new URL('/login', request.url))`。示例:`if (!isAuthenticated && request.nextUrl.pathname !== '/login') { return NextResponse.redirect(...) }`。
无效尝试
常见但无效的做法:
-
100% 失败
The check does not prevent the redirect; it still redirects to the same path, causing an infinite loop.
-
90% 失败
If the user is already on /login, the redirect will point back to /login, creating a loop.
-
70% 失败
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.