nextjs runtime_error ai_generated true

错误:中间件重定向到外部 URL。重定向必须是相对路径或内部路由。

Error: Middleware redirected to an external URL. Redirects must be to relative paths or internal routes.

ID: nextjs/middleware-redirect-to-external-url

其他格式: JSON · Markdown 中文 · English
90%修复率
88%置信度
1证据数
2023-10-01首次发现

版本兼容性

版本状态引入弃用备注
13.5.0 active
14.0.0 active
14.1.0 active
15.0.0 active

根因分析

Next.js 中间件限制 NextResponse.redirect() 方法仅接受相对 URL 或同一应用程序内的路径,以防止开放重定向的安全问题。

English

Next.js middleware restricts the NextResponse.redirect() method to only accept relative URLs or paths within the same application, preventing security issues from open redirects.

generic

官方文档

https://nextjs.org/docs/app/building-your-application/routing/middleware#nextresponseredirect

解决方案

  1. Redirect to a relative path within your app and then handle the external redirect on the client side using useEffect or a Server Action. Example: export function middleware(request) { return NextResponse.redirect(new URL('/external-redirect', request.url)); } Then in the /external-redirect page, call window.location.href = 'https://example.com'.
  2. Use NextResponse.next() and set a custom header to signal the client to redirect, then read that header in a layout or page component.

无效尝试

常见但无效的做法:

  1. Using window.location.href inside middleware to redirect externally 100% 失败

    Middleware runs on the server/edge runtime, not in the browser. window is not defined.

  2. Setting the Location header manually in the middleware response 80% 失败

    Next.js middleware response headers are immutable for security; manual header manipulation is ignored or causes a different error.