nextjs
runtime_error
ai_generated
true
错误:服务器操作无法重定向到外部 URL。请改用 NextResponse.redirect()。
Error: Server Actions cannot redirect to external URLs. Use NextResponse.redirect() instead.
ID: nextjs/server-action-redirect-external
90%修复率
85%置信度
1证据数
2024-08-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| [email protected] | active | — | — | — |
| [email protected] | active | — | — | — |
根因分析
服务器操作使用 'use server' 指令,只能通过 redirect() 重定向到内部路由。外部 URL 需要不同的方法,例如在中间件中使用 NextResponse.redirect() 或客户端重定向。
English
Server Actions use the 'use server' directive and can only redirect to internal routes using redirect(). External URLs require a different approach, such as NextResponse.redirect() in middleware or a client-side redirect.
官方文档
https://nextjs.org/docs/app/api-reference/functions/server-actions#redirecting解决方案
-
从服务器操作返回重定向 URL,并在客户端使用 useRouter 或 window.location 处理重定向。
-
在中间件中使用 NextResponse.redirect(),并通过服务器操作设置的自定义 header 触发。
无效尝试
常见但无效的做法:
-
95% 失败
Server Actions run on the server; window is not defined, causing a ReferenceError.
-
70% 失败
This adds complexity and may not work with Next.js error boundaries, leading to unhandled rejections.