mirror of
https://github.com/vercel/next.js.git
synced 2026-09-20 02:25:18 +08:00
71ce95dffa
> [!NOTE] > Best reviewed by each commit for better diff view. This PR clones the Middleware docs for Proxy and removes the Middleware docs. Did not clone the list of docs: - `errors/middleware-upgrade.mdx` - It's a middleware upgrade guide from v12.2 - `errors/beta-middleware.mdx` - It's an error when using middleware before v12.2 - `errors/returning-response-body.mdx` - Legacy behavior from versions < v12.2
41 lines
1.6 KiB
Plaintext
41 lines
1.6 KiB
Plaintext
---
|
|
title: Proxy Relative URLs
|
|
---
|
|
|
|
## Why This Error Occurred
|
|
|
|
You are using a Proxy 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 Proxy, 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="proxy.ts"
|
|
import type { NextRequest } from 'next/server'
|
|
import { NextResponse } from 'next/server'
|
|
|
|
export function proxy(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="proxy.ts"
|
|
import type { NextRequest } from 'next/server'
|
|
import { NextResponse } from 'next/server'
|
|
|
|
export function proxy(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)
|