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

- **ID:** `nextjs/middleware-redirect-to-external-url`
- **Domain:** nextjs
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 90%

## 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.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 13.5.0 | active | — | — |
| 14.0.0 | active | — | — |
| 14.1.0 | active | — | — |
| 15.0.0 | active | — | — |

## Workarounds

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'.** (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'.
   ```
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.** (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.
   ```

## Dead Ends

- **Using window.location.href inside middleware to redirect externally** — Middleware runs on the server/edge runtime, not in the browser. window is not defined. (100% fail)
- **Setting the Location header manually in the middleware response** — Next.js middleware response headers are immutable for security; manual header manipulation is ignored or causes a different error. (80% fail)
