rsnext/errors/middleware-relative-urls.mdx
Michael Novotny fe797c1074
Updates Mozilla links to not include language preference (#55326)
Internal suggestion to remove `en-US` from Mozilla urls since MDN is
available in multiple languages nowadays it will automatically redirect
to the viewer’s language preference.

Closes
[DX-2076](https://linear.app/vercel/issue/DX-2076/make-external-mozilla-links-language-agnostic-in-nextjs-docs)
2023-09-13 11:06:29 -05:00

40 lines
1.6 KiB
Text

---
title: Middleware Relative URLs
---
## Why This Error Occurred
You are using a Middleware function that uses `Response.redirect(url)`, `NextResponse.redirect(url)` or `NextResponse.rewrite(url)` where `url` is a relative or an invalid URL. Prior to Next.js 12.1, we allowed passing relative URLs. However, constructing a request with `new Request(url)` or running `fetch(url)` when `url` is a relative URL **does not** work. For this reason and to bring consistency to Next.js Middleware, this behavior has been deprecated and now removed.
## Possible Ways to Fix It
To fix this error you must always pass absolute URL for redirecting and rewriting. There are several ways to get the absolute URL but the recommended way is to clone `NextURL` and mutate it:
```ts filename="middleware.ts"
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
export function middleware(request: NextRequest) {
const url = request.nextUrl.clone()
url.pathname = '/dest'
return NextResponse.rewrite(url)
}
```
Another way to fix this error could be to use the original URL as the base but this will not consider configuration like `basePath` or `locale`:
```ts filename="middleware.ts"
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
export function middleware(request: NextRequest) {
return NextResponse.rewrite(new URL('/dest', request.url))
}
```
You can also pass directly a string containing a valid absolute URL.
## Useful Links
- [URL Documentation](https://developer.mozilla.org/docs/Web/API/URL)
- [Response Documentation](https://developer.mozilla.org/docs/Web/API/Response)