nextjs runtime_error ai_generated true

Error: Server Actions cannot redirect to external URLs. Use NextResponse.redirect() instead.

ID: nextjs/server-action-redirect-external

Also available as: JSON · Markdown · 中文
90%Fix Rate
85%Confidence
1Evidence
2024-08-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
[email protected] active
[email protected] active

Root Cause

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.

generic

中文

服务器操作使用 'use server' 指令,只能通过 redirect() 重定向到内部路由。外部 URL 需要不同的方法,例如在中间件中使用 NextResponse.redirect() 或客户端重定向。

Official Documentation

https://nextjs.org/docs/app/api-reference/functions/server-actions#redirecting

Workarounds

  1. 90% success Return a redirect URL from the Server Action and handle the redirect on the client side using useRouter or window.location.
    Return a redirect URL from the Server Action and handle the redirect on the client side using useRouter or window.location.
  2. 80% success Use NextResponse.redirect() in middleware with a custom header set by the Server Action.
    Use NextResponse.redirect() in middleware with a custom header set by the Server Action.

中文步骤

  1. 从服务器操作返回重定向 URL,并在客户端使用 useRouter 或 window.location 处理重定向。
  2. 在中间件中使用 NextResponse.redirect(),并通过服务器操作设置的自定义 header 触发。

Dead Ends

Common approaches that don't work:

  1. 95% fail

    Server Actions run on the server; window is not defined, causing a ReferenceError.

  2. 70% fail

    This adds complexity and may not work with Next.js error boundaries, leading to unhandled rejections.