nextjs runtime_error ai_generated true

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

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

Also available as: JSON · Markdown · 中文
90%Fix Rate
88%Confidence
1Evidence
2023-10-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
13.5.0 active
14.0.0 active
14.1.0 active
15.0.0 active

Root Cause

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

中文

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

Official Documentation

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

Workarounds

  1. 90% success 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'.
    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. 85% success Use NextResponse.next() and set a custom header to signal the client to redirect, then read that header in a layout or page component.
    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. 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.

Dead Ends

Common approaches that don't work:

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

    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% fail

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