rsnext/errors/middleware-relative-urls.md
Gal Schlezinger f0f322c0d1
Remove deprecation for relative URL usage in middlewares (#34461)
* Remove deprecation for relative URL usage in middlewares

* fix tests

Co-authored-by: JJ Kasper <jj@jjsweb.site>
2022-02-17 09:12:36 -06:00

38 lines
1.6 KiB
Markdown

# 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:
```typescript
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`:
```typescript
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/en-US/docs/Web/API/URL)
- [Response Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Response)