Unverified Commit 71ce95df authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

docs: Replace Middleware docs to Proxy (#84709)

> [!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
parent fd8b4c59
......@@ -8,7 +8,7 @@ related:
- app/api-reference/functions/next-response
---
The `middleware.js|ts` file is used to write [Middleware](/docs/app/getting-started/route-handlers-and-middleware#middleware) and run code on the server before a request is completed. Then, based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly.
The `middleware.js|ts` file is used to write [Middleware](/docs/app/getting-started/#middleware) and run code on the server before a request is completed. Then, based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly.
Middleware executes before routes are rendered. It's particularly useful for implementing custom server-side logic like authentication, logging, or handling redirects.
......@@ -353,7 +353,7 @@ export function middleware(request) {
})
cookie = response.cookies.get('vercel')
console.log(cookie) // => { name: 'vercel', value: 'fast', Path: '/' }
// The outgoing response will have a `Set-Cookie:vercel=fast;path=/test` header.
// The outgoing response will have a `Set-Cookie:vercel=fast;path=/` header.
return response
}
......
This diff is collapsed.
---
title: Proxy
description: Learn how to use Proxy to run code before a request is completed.
source: app/api-reference/file-conventions/proxy
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
......@@ -14,7 +14,7 @@ import { NextResponse } from 'next/server'
export default function middleware(request: NextRequest) {
const nextUrl = request.nextUrl
nextUrl.searchParams.delete('key') // <-- this is now possible! 🎉
nextUrl.searchParams.delete('key') // <-- this is now possible!
return NextResponse.rewrite(nextUrl)
}
```
......
---
title: Deleting Query Parameters In Proxies
---
## Why This Error Occurred
In previous versions of Next.js, we were merging query parameters with the incoming request for rewrites happening in proxies, to match the behavior of static rewrites declared in the config. This forced Next.js users to use empty query parameters values to delete keys.
We are changing this behavior to allow extra flexibility and a more streamlined experience for users. So from now on, query parameters will not be merged and thus the warning.
```ts filename="proxy.ts"
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
export default function proxy(request: NextRequest) {
const nextUrl = request.nextUrl
nextUrl.searchParams.delete('key') // <-- this is now possible!
return NextResponse.rewrite(nextUrl)
}
```
## Possible Ways to Fix It
If you are relying on the old behavior, please add the query parameters manually to the rewritten URL. Using `request.nextUrl` would do that automatically for you.
```ts filename="proxy.ts"
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
export default function proxy(request: NextRequest) {
const nextUrl = request.nextUrl
nextUrl.pathname = '/dest'
return NextResponse.rewrite(nextUrl)
}
```
This warning will be removed in the next version of Next.js.
......@@ -13,7 +13,7 @@ export function middleware(request: NextRequest) {
const viewport = request.ua.device.type === 'mobile' ? 'mobile' : 'desktop'
request.nextUrl.searchParams.set('viewport', viewport)
return NextResponse.rewrites(request.nextUrl)
return NextResponse.rewrite(request.nextUrl)
}
```
......
......@@ -10,7 +10,7 @@ Your application is interacting with `request.page` which has been deprecated.
import { NextRequest, NextResponse } from 'next/server'
export function middleware(request: NextRequest) {
const { params } = event.request.page
const { params } = request.page
const { locale, slug } = params
if (locale && slug) {
......
---
title: Nested Proxy
---
## Why This Error Occurred
You are defining a Proxy file in a location different from `<root>/proxy`, which is not allowed.
While in beta, a Proxy file under specific pages would _only_ be executed when pages below its declaration were matched, allowing nesting Proxy files. Based on customer feedback, we have replaced this API with a single root Proxy.
## Possible Ways to Fix It
Declare your Proxy in the root folder and use `NextRequest` parsed URL to define which path the Proxy should be executed for.
For example, a Proxy at `pages/about/_proxy.ts` can move the logic to `<root>/proxy.ts` in the root of your repository. Then, a conditional statement can be used to only run the Proxy when it matches the `about/*` path:
```ts filename="proxy.ts"
import type { NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
if (request.nextUrl.pathname.startsWith('/about')) {
// This logic is only applied to /about
}
if (request.nextUrl.pathname.startsWith('/dashboard')) {
// This logic is only applied to /dashboard
}
}
```
If you have more than one Proxy, you should combine them into a single file and model their execution depending on the incoming request.
---
title: Dynamic WASM compilation is not available in Proxies
---
## Why This Error Occurred
Compiling WASM binaries dynamically is not allowed in Proxies. Specifically,
the following APIs are not supported:
- `WebAssembly.compile`
- `WebAssembly.instantiate` with [a buffer parameter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate#primary_overload_%E2%80%94_taking_wasm_binary_code)
## Possible Ways to Fix It
Bundle your WASM binaries using `import`:
```ts filename="proxy.ts"
import { NextResponse } from 'next/server'
import squareWasm from './square.wasm?module'
export default async function proxy() {
const m = await WebAssembly.instantiate(squareWasm)
const answer = m.exports.square(9)
const response = NextResponse.next()
response.headers.set('x-square', answer.toString())
return response
}
```
---
title: Deprecated Proxy API Signature
---
## Why This Error Occurred
Your application is using a Proxy function that is using parameters from the deprecated API.
```ts filename="proxy.ts"
import { NextResponse } from 'next/server'
export function proxy(event) {
if (event.request.nextUrl.pathname === '/blocked') {
event.respondWith(
new NextResponse(null, {
status: 403,
})
)
}
}
```
## Possible Ways to Fix It
Update to use the new API for Proxy:
```ts filename="proxy.ts"
import { NextResponse } from 'next/server'
export function proxy(request) {
if (request.nextUrl.pathname === '/blocked') {
return new NextResponse(null, {
status: 403,
})
}
}
```
---
title: Removed parsed User Agent from Proxy API
---
## Why This Error Occurred
Your application is interacting with `req.ua` which has been deprecated.
```ts filename="proxy.ts"
import { NextRequest, NextResponse } from 'next/server'
export function proxy(request: NextRequest) {
const viewport = request.ua.device.type === 'mobile' ? 'mobile' : 'desktop'
request.nextUrl.searchParams.set('viewport', viewport)
return NextResponse.rewrite(request.nextUrl)
}
```
## Possible Ways to Fix It
The internal logic has been moved into a separate `userAgent` function that you can import from `next/server` and wrap your request instead.
```ts filename="proxy.ts"
import { NextRequest, NextResponse, userAgent } from 'next/server'
export function proxy(request: NextRequest) {
const { device } = userAgent(request)
const viewport = device.type === 'mobile' ? 'mobile' : 'desktop'
request.nextUrl.searchParams.set('viewport', viewport)
return NextResponse.rewrite(request.nextUrl)
}
```
---
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)
---
title: Removed page from Proxy API
---
## Why This Error Occurred
Your application is interacting with `request.page` which has been deprecated.
```ts filename="proxy.ts"
import { NextRequest, NextResponse } from 'next/server'
export function proxy(request: NextRequest) {
const { params } = request.page
const { locale, slug } = params
if (locale && slug) {
const { search, protocol, host } = request.nextUrl
const url = new URL(`${protocol}//${locale}.${host}/${slug}${search}`)
return NextResponse.redirect(url)
}
}
```
## Possible Ways to Fix It
You can use [URLPattern](https://developer.mozilla.org/docs/Web/API/URLPattern) instead to have the same behavior:
```ts filename="proxy.ts"
import { NextRequest, NextResponse } from 'next/server'
const PATTERNS = [
[
new URLPattern({ pathname: '/:locale/:slug' }),
({ pathname }) => pathname.groups,
],
]
const params = (url) => {
const input = url.split('?')[0]
let result = {}
for (const [pattern, handler] of PATTERNS) {
const patternResult = pattern.exec(input)
if (patternResult !== null && 'pathname' in patternResult) {
result = handler(patternResult)
break
}
}
return result
}
export function proxy(request: NextRequest) {
const { locale, slug } = params(request.url)
if (locale && slug) {
const { search, protocol, host } = request.nextUrl
const url = new URL(`${protocol}//${locale}.${host}/${slug}${search}`)
return NextResponse.redirect(url)
}
}
```
---
title: Removed req.ua from Proxy API
---
## Why This Error Occurred
Your proxy is interacting with `req.ua` and this feature needs to opt-in.
```ts filename="proxy.ts"
import { NextRequest, NextResponse } from 'next/server'
export function proxy(request: NextRequest) {
const url = request.nextUrl
const viewport = request.ua.device.type === 'mobile' ? 'mobile' : 'desktop'
url.searchParams.set('viewport', viewport)
return NextResponse.rewrite(url)
}
```
## Possible Ways to Fix It
To parse the user agent, import `userAgent` function from `next/server` and give it your request:
```ts filename="proxy.ts"
import { NextRequest, NextResponse, userAgent } from 'next/server'
export function proxy(request: NextRequest) {
const url = request.nextUrl
const { device } = userAgent(request)
const viewport = device.type === 'mobile' ? 'mobile' : 'desktop'
url.searchParams.set('viewport', viewport)
return NextResponse.rewrite(url)
}
```
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment