Unverified Commit bc59f210 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

docs: Deprecation of Middleware (#84710)

This PR removes middleware docs and adds a "Migration to Proxy" section
to the Proxy docs, which explains the rationale for the renaming to
Proxy and provides a migration guide.

Did not remove `middleware-upgrade-docs` as it's an upgrade doc from the
legacy middleware.

Below are untouched as they need codebase changes:

- `instrumentation` docs - `onRequestError` has `context.routeType` as
`'middleware'`
- `adapterPath` docs - has `MiddlewareMatcher` type example
- `ProxyConfig` - has a user-facing `MiddlewareMatcher` type

---------
Co-authored-by: 's avatarJoseph Chamochumbi <joseph.chamochumbi@vercel.com>
parent 3129db08
...@@ -29,7 +29,7 @@ Top-level folders are used to organize your application's code and static assets ...@@ -29,7 +29,7 @@ Top-level folders are used to organize your application's code and static assets
### Top-level files ### Top-level files
Top-level files are used to configure your application, manage dependencies, run middleware, integrate monitoring tools, and define environment variables. Top-level files are used to configure your application, manage dependencies, run proxy, integrate monitoring tools, and define environment variables.
| | | | | |
| ---------------------------------------------------------------------------- | --------------------------------------- | | ---------------------------------------------------------------------------- | --------------------------------------- |
...@@ -37,7 +37,7 @@ Top-level files are used to configure your application, manage dependencies, run ...@@ -37,7 +37,7 @@ Top-level files are used to configure your application, manage dependencies, run
| [`next.config.js`](/docs/app/api-reference/config/next-config-js) | Configuration file for Next.js | | [`next.config.js`](/docs/app/api-reference/config/next-config-js) | Configuration file for Next.js |
| [`package.json`](/docs/app/getting-started/installation#manual-installation) | Project dependencies and scripts | | [`package.json`](/docs/app/getting-started/installation#manual-installation) | Project dependencies and scripts |
| [`instrumentation.ts`](/docs/app/guides/instrumentation) | OpenTelemetry and Instrumentation file | | [`instrumentation.ts`](/docs/app/guides/instrumentation) | OpenTelemetry and Instrumentation file |
| [`middleware.ts`](/docs/app/api-reference/file-conventions/middleware) | Next.js request middleware | | [`proxy.ts`](/docs/app/api-reference/file-conventions/proxy) | Next.js request proxy |
| [`.env`](/docs/app/guides/environment-variables) | Environment variables | | [`.env`](/docs/app/guides/environment-variables) | Environment variables |
| [`.env.local`](/docs/app/guides/environment-variables) | Local environment variables | | [`.env.local`](/docs/app/guides/environment-variables) | Local environment variables |
| [`.env.production`](/docs/app/guides/environment-variables) | Production environment variables | | [`.env.production`](/docs/app/guides/environment-variables) | Production environment variables |
......
...@@ -6,8 +6,7 @@ related: ...@@ -6,8 +6,7 @@ related:
title: API Reference title: API Reference
description: Learn more about Proxy description: Learn more about Proxy
links: links:
# TODO: Update to proxy docs - app/api-reference/file-conventions/proxy
- app/api-reference/file-conventions/middleware
- app/guides/backend-for-frontend - app/guides/backend-for-frontend
--- ---
...@@ -67,6 +66,4 @@ export const config = { ...@@ -67,6 +66,4 @@ export const config = {
} }
``` ```
{/* TODO: Update to proxy docs */} Read more about [using `proxy`](/docs/app/guides/backend-for-frontend#proxy), or refer to the `proxy` [API reference](/docs/app/api-reference/file-conventions/proxy).
Read more about [using `proxy`](/docs/app/guides/backend-for-frontend#middleware), or refer to the `proxy` [API reference](/docs/app/api-reference/file-conventions/middleware).
...@@ -871,7 +871,7 @@ To create and manage database sessions, you'll need to follow these steps: ...@@ -871,7 +871,7 @@ To create and manage database sessions, you'll need to follow these steps:
1. Create a table in your database to store session and data (or check if your Auth Library handles this). 1. Create a table in your database to store session and data (or check if your Auth Library handles this).
2. Implement functionality to insert, update, and delete sessions 2. Implement functionality to insert, update, and delete sessions
3. Encrypt the session ID before storing it in the user's browser, and ensure the database and cookie stay in sync (this is optional, but recommended for optimistic auth checks in [Middleware](#optimistic-checks-with-middleware-optional)). 3. Encrypt the session ID before storing it in the user's browser, and ensure the database and cookie stay in sync (this is optional, but recommended for optimistic auth checks in [Proxy](#optimistic-checks-with-proxy-optional)).
<AppOnly> <AppOnly>
...@@ -1019,20 +1019,20 @@ For both cases, we recommend: ...@@ -1019,20 +1019,20 @@ For both cases, we recommend:
- Creating a [Data Access Layer](#creating-a-data-access-layer-dal) to centralize your authorization logic - Creating a [Data Access Layer](#creating-a-data-access-layer-dal) to centralize your authorization logic
- Using [Data Transfer Objects (DTO)](#using-data-transfer-objects-dto) to only return the necessary data - Using [Data Transfer Objects (DTO)](#using-data-transfer-objects-dto) to only return the necessary data
- Optionally use [Middleware](#optimistic-checks-with-middleware-optional) to perform optimistic checks. - Optionally use [Proxy](#optimistic-checks-with-proxy-optional) to perform optimistic checks.
### Optimistic checks with Middleware (Optional) ### Optimistic checks with Proxy (Optional)
There are some cases where you may want to use [Middleware](/docs/app/api-reference/file-conventions/middleware) and redirect users based on permissions: There are some cases where you may want to use [Proxy](/docs/app/api-reference/file-conventions/proxy) and redirect users based on permissions:
- To perform optimistic checks. Since Middleware runs on every route, it's a good way to centralize redirect logic and pre-filter unauthorized users. - To perform optimistic checks. Since Proxy runs on every route, it's a good way to centralize redirect logic and pre-filter unauthorized users.
- To protect static routes that share data between users (e.g. content behind a paywall). - To protect static routes that share data between users (e.g. content behind a paywall).
However, since Middleware runs on every route, including [prefetched](/docs/app/getting-started/linking-and-navigating#prefetching) routes, it's important to only read the session from the cookie (optimistic checks), and avoid database checks to prevent performance issues. However, since Proxy runs on every route, including [prefetched](/docs/app/getting-started/linking-and-navigating#prefetching) routes, it's important to only read the session from the cookie (optimistic checks), and avoid database checks to prevent performance issues.
For example: For example:
```tsx filename="middleware.ts" switcher ```tsx filename="proxy.ts" switcher
import { NextRequest, NextResponse } from 'next/server' import { NextRequest, NextResponse } from 'next/server'
import { decrypt } from '@/app/lib/session' import { decrypt } from '@/app/lib/session'
import { cookies } from 'next/headers' import { cookies } from 'next/headers'
...@@ -1041,7 +1041,7 @@ import { cookies } from 'next/headers' ...@@ -1041,7 +1041,7 @@ import { cookies } from 'next/headers'
const protectedRoutes = ['/dashboard'] const protectedRoutes = ['/dashboard']
const publicRoutes = ['/login', '/signup', '/'] const publicRoutes = ['/login', '/signup', '/']
export default async function middleware(req: NextRequest) { export default async function proxy(req: NextRequest) {
// 2. Check if the current route is protected or public // 2. Check if the current route is protected or public
const path = req.nextUrl.pathname const path = req.nextUrl.pathname
const isProtectedRoute = protectedRoutes.includes(path) const isProtectedRoute = protectedRoutes.includes(path)
...@@ -1068,13 +1068,13 @@ export default async function middleware(req: NextRequest) { ...@@ -1068,13 +1068,13 @@ export default async function middleware(req: NextRequest) {
return NextResponse.next() return NextResponse.next()
} }
// Routes Middleware should not run on // Routes Proxy should not run on
export const config = { export const config = {
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'], matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
} }
``` ```
```js filename="middleware.js" switcher ```js filename="proxy.js" switcher
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
import { decrypt } from '@/app/lib/session' import { decrypt } from '@/app/lib/session'
import { cookies } from 'next/headers' import { cookies } from 'next/headers'
...@@ -1083,7 +1083,7 @@ import { cookies } from 'next/headers' ...@@ -1083,7 +1083,7 @@ import { cookies } from 'next/headers'
const protectedRoutes = ['/dashboard'] const protectedRoutes = ['/dashboard']
const publicRoutes = ['/login', '/signup', '/'] const publicRoutes = ['/login', '/signup', '/']
export default async function middleware(req) { export default async function proxy(req) {
// 2. Check if the current route is protected or public // 2. Check if the current route is protected or public
const path = req.nextUrl.pathname const path = req.nextUrl.pathname
const isProtectedRoute = protectedRoutes.includes(path) const isProtectedRoute = protectedRoutes.includes(path)
...@@ -1110,19 +1110,19 @@ export default async function middleware(req) { ...@@ -1110,19 +1110,19 @@ export default async function middleware(req) {
return NextResponse.next() return NextResponse.next()
} }
// Routes Middleware should not run on // Routes Proxy should not run on
export const config = { export const config = {
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'], matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
} }
``` ```
While Middleware can be useful for initial checks, it should not be your only line of defense in protecting your data. The majority of security checks should be performed as close as possible to your data source, see [Data Access Layer](#creating-a-data-access-layer-dal) for more information. While Proxy can be useful for initial checks, it should not be your only line of defense in protecting your data. The majority of security checks should be performed as close as possible to your data source, see [Data Access Layer](#creating-a-data-access-layer-dal) for more information.
> **Tips**: > **Tips**:
> >
> - In Middleware, you can also read cookies using `req.cookies.get('session').value`. > - In Proxy, you can also read cookies using `req.cookies.get('session').value`.
> - Middleware uses the [Edge Runtime](/docs/app/api-reference/edge), check if your Auth library and session management library are compatible. > - Proxy uses the [Edge Runtime](/docs/app/api-reference/edge), check if your Auth library and session management library are compatible.
> - You can use the `matcher` property in the Middleware to specify which routes Middleware should run on. Although, for auth, it's recommended Middleware runs on all routes. > - You can use the `matcher` property in the Proxy to specify which routes Proxy should run on. Although, for auth, it's recommended Proxy runs on all routes.
<AppOnly> <AppOnly>
...@@ -1226,7 +1226,7 @@ export const getUser = cache(async () => { ...@@ -1226,7 +1226,7 @@ export const getUser = cache(async () => {
> **Tip**: > **Tip**:
> >
> - A DAL can be used to protect data fetched at request time. However, for static routes that share data between users, data will be fetched at build time and not at request time. Use [Middleware](#optimistic-checks-with-middleware-optional) to protect static routes. > - A DAL can be used to protect data fetched at request time. However, for static routes that share data between users, data will be fetched at build time and not at request time. Use [Proxy](#optimistic-checks-with-proxy-optional) to protect static routes.
> - For secure checks, you can check if the session is valid by comparing the session ID with your database. Use React's [cache](https://react.dev/reference/react/cache) function to avoid unnecessary duplicate requests to the database during a render pass. > - For secure checks, you can check if the session is valid by comparing the session ID with your database. Use React's [cache](https://react.dev/reference/react/cache) function to avoid unnecessary duplicate requests to the database during a render pass.
> - You may wish to consolidate related data requests in a JavaScript class that runs `verifySession()` before any methods. > - You may wish to consolidate related data requests in a JavaScript class that runs `verifySession()` before any methods.
......
...@@ -4,10 +4,10 @@ nav_title: Backend for Frontend ...@@ -4,10 +4,10 @@ nav_title: Backend for Frontend
description: Learn how to use Next.js as a backend framework description: Learn how to use Next.js as a backend framework
related: related:
title: API Reference title: API Reference
description: Learn more about Route Handlers and Middleware description: Learn more about Route Handlers and Proxy
links: links:
- app/api-reference/file-conventions/route - app/api-reference/file-conventions/route
- app/api-reference/file-conventions/middleware - app/api-reference/file-conventions/proxy
--- ---
Next.js supports the "Backend for Frontend" pattern. This lets you create public endpoints to handle HTTP requests and return any content type—not just HTML. You can also access data sources and perform side effects like updating remote data. Next.js supports the "Backend for Frontend" pattern. This lets you create public endpoints to handle HTTP requests and return any content type—not just HTML. You can also access data sources and perform side effects like updating remote data.
...@@ -27,7 +27,7 @@ npx create-next-app@latest --api ...@@ -27,7 +27,7 @@ npx create-next-app@latest --api
To implement this pattern, use: To implement this pattern, use:
- [Route Handlers](/docs/app/api-reference/file-conventions/route) - [Route Handlers](/docs/app/api-reference/file-conventions/route)
- [`middleware`](/docs/app/api-reference/file-conventions/middleware) - [`proxy`](/docs/app/api-reference/file-conventions/proxy)
- In Pages Router, [API Routes](/docs/pages/building-your-application/routing/api-routes) - In Pages Router, [API Routes](/docs/pages/building-your-application/routing/api-routes)
## Public Endpoints ## Public Endpoints
...@@ -330,7 +330,7 @@ export async function POST(request) { ...@@ -330,7 +330,7 @@ export async function POST(request) {
## Proxying to a backend ## Proxying to a backend
You can use a Route Handler as a proxy to another backend. Add validation logic before forwarding the request. You can use a Route Handler as a `proxy` to another backend. Add validation logic before forwarding the request.
```ts filename="/app/api/[...slug]/route.ts" switcher ```ts filename="/app/api/[...slug]/route.ts" switcher
import { isValidRequest } from '@/lib/utils' import { isValidRequest } from '@/lib/utils'
...@@ -388,12 +388,12 @@ export async function POST(request, { params }) { ...@@ -388,12 +388,12 @@ export async function POST(request, { params }) {
Or use: Or use:
- `middleware` [rewrites](#middleware) - `proxy` [rewrites](#proxy)
- [`rewrites`](/docs/app/api-reference/config/next-config-js/rewrites) in `next.config.js`. - [`rewrites`](/docs/app/api-reference/config/next-config-js/rewrites) in `next.config.js`.
## NextRequest and NextResponse ## NextRequest and NextResponse
Next.js extends the [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) and [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) Web APIs with methods that simplify common operations. These extensions are available in both Route Handlers and Middleware. Next.js extends the [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) and [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) Web APIs with methods that simplify common operations. These extensions are available in both Route Handlers and Proxy.
Both provide methods for reading and manipulating cookies. Both provide methods for reading and manipulating cookies.
...@@ -557,20 +557,20 @@ export async function GET(request) { ...@@ -557,20 +557,20 @@ export async function GET(request) {
Learn more about redirects in [`redirect`](/docs/app/api-reference/functions/redirect) and [`permanentRedirect`](/docs/app/api-reference/functions/permanentRedirect) Learn more about redirects in [`redirect`](/docs/app/api-reference/functions/redirect) and [`permanentRedirect`](/docs/app/api-reference/functions/permanentRedirect)
## Middleware ## Proxy
Only one middleware file is allowed per project. Use `config.matcher` to target specific paths. Learn more about [middleware](/docs/app/api-reference/file-conventions/middleware). Only one `proxy` file is allowed per project. Use `config.matcher` to target specific paths. Learn more about [`proxy`](/docs/app/api-reference/file-conventions/proxy).
Use `middleware` to generate a response before the request reaches a route path. Use `proxy` to generate a response before the request reaches a route path.
```ts filename="middleware.ts" switcher ```ts filename="proxy.ts" switcher
import { isAuthenticated } from '@lib/auth' import { isAuthenticated } from '@lib/auth'
export const config = { export const config = {
matcher: '/api/:function*', matcher: '/api/:function*',
} }
export function middleware(request: Request) { export function proxy(request: Request) {
if (!isAuthenticated(request)) { if (!isAuthenticated(request)) {
return Response.json( return Response.json(
{ success: false, message: 'authentication failed' }, { success: false, message: 'authentication failed' },
...@@ -580,14 +580,14 @@ export function middleware(request: Request) { ...@@ -580,14 +580,14 @@ export function middleware(request: Request) {
} }
``` ```
```js filename="middleware.js" switcher ```js filename="proxy.js" switcher
import { isAuthenticated } from '@lib/auth' import { isAuthenticated } from '@lib/auth'
export const config = { export const config = {
matcher: '/api/:function*', matcher: '/api/:function*',
} }
export function middleware(request) { export function proxy(request) {
if (!isAuthenticated(request)) { if (!isAuthenticated(request)) {
return Response.json( return Response.json(
{ success: false, message: 'authentication failed' }, { success: false, message: 'authentication failed' },
...@@ -597,12 +597,12 @@ export function middleware(request) { ...@@ -597,12 +597,12 @@ export function middleware(request) {
} }
``` ```
You can also proxy requests using `middleware`: You can also proxy requests using `proxy`:
```ts filename="middleware.ts" switcher ```ts filename="proxy.ts" switcher
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
export function middleware(request: Request) { export function proxy(request: Request) {
if (request.nextUrl.pathname === '/proxy-this-path') { if (request.nextUrl.pathname === '/proxy-this-path') {
const rewriteUrl = new URL('https://nextjs.org') const rewriteUrl = new URL('https://nextjs.org')
return NextResponse.rewrite(rewriteUrl) return NextResponse.rewrite(rewriteUrl)
...@@ -610,10 +610,10 @@ export function middleware(request: Request) { ...@@ -610,10 +610,10 @@ export function middleware(request: Request) {
} }
``` ```
```js filename="middleware.js" switcher ```js filename="proxy.js" switcher
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
export function middleware(request) { export function proxy(request) {
if (request.nextUrl.pathname === '/proxy-this-path') { if (request.nextUrl.pathname === '/proxy-this-path') {
const rewriteUrl = new URL('https://nextjs.org') const rewriteUrl = new URL('https://nextjs.org')
return NextResponse.rewrite(rewriteUrl) return NextResponse.rewrite(rewriteUrl)
...@@ -621,12 +621,12 @@ export function middleware(request) { ...@@ -621,12 +621,12 @@ export function middleware(request) {
} }
``` ```
Another type of response `middleware` can produce are redirects: Another type of response `proxy` can produce are redirects:
```ts filename="middleware.ts" switcher ```ts filename="proxy.ts" switcher
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
export function middleware(request: Request) { export function proxy(request: Request) {
if (request.nextUrl.pathname === '/v1/docs') { if (request.nextUrl.pathname === '/v1/docs') {
request.nextUrl.pathname = '/v2/docs' request.nextUrl.pathname = '/v2/docs'
return NextResponse.redirect(request.nextUrl) return NextResponse.redirect(request.nextUrl)
...@@ -634,10 +634,10 @@ export function middleware(request: Request) { ...@@ -634,10 +634,10 @@ export function middleware(request: Request) {
} }
``` ```
```js filename="middleware.js" switcher ```js filename="proxy.js" switcher
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
export function middleware(request) { export function proxy(request) {
if (request.nextUrl.pathname === '/v1/docs') { if (request.nextUrl.pathname === '/v1/docs') {
request.nextUrl.pathname = '/v2/docs' request.nextUrl.pathname = '/v2/docs'
return NextResponse.redirect(request.nextUrl) return NextResponse.redirect(request.nextUrl)
...@@ -651,10 +651,10 @@ export function middleware(request) { ...@@ -651,10 +651,10 @@ export function middleware(request) {
Be deliberate about where headers go, and avoid directly passing incoming request headers to the outgoing response. Be deliberate about where headers go, and avoid directly passing incoming request headers to the outgoing response.
- **Upstream request headers**: In Middleware, `NextResponse.next({ request: { headers } })` modifies the headers your server receives and does not expose them to the client. - **Upstream request headers**: In Proxy, `NextResponse.next({ request: { headers } })` modifies the headers your server receives and does not expose them to the client.
- **Response headers**: `new Response(..., { headers })`, `NextResponse.json(..., { headers })`, `NextResponse.next({ headers })`, or `response.headers.set(...)` send headers back to the client. If sensitive values were appended to these headers, they will be visible to clients. - **Response headers**: `new Response(..., { headers })`, `NextResponse.json(..., { headers })`, `NextResponse.next({ headers })`, or `response.headers.set(...)` send headers back to the client. If sensitive values were appended to these headers, they will be visible to clients.
Learn more in [NextResponse headers in Middleware](/docs/app/api-reference/functions/next-response#next). Learn more in [NextResponse headers in Proxy](/docs/app/api-reference/functions/next-response#next).
### Rate limiting ### Rate limiting
...@@ -700,7 +700,7 @@ Store user-generated static assets in dedicated services. When possible, upload ...@@ -700,7 +700,7 @@ Store user-generated static assets in dedicated services. When possible, upload
### Access to protected resources ### Access to protected resources
Always verify credentials before granting access. Do not rely on middleware alone for authentication and authorization. Always verify credentials before granting access. Do not rely on proxy alone for authentication and authorization.
Remove sensitive or unnecessary data from responses and backend logs. Remove sensitive or unnecessary data from responses and backend logs.
...@@ -732,19 +732,21 @@ export { handler as POST } ...@@ -732,19 +732,21 @@ export { handler as POST }
This creates a shared handler for `GET` and `POST` requests. The library customizes behavior based on the `method` and `pathname` in the request. This creates a shared handler for `GET` and `POST` requests. The library customizes behavior based on the `method` and `pathname` in the request.
Libraries can also provide a `middleware` factory. Libraries can also provide a `proxy` factory.
```ts filename="middleware.ts" ```ts filename="proxy.ts"
import { createMiddleware } from 'third-party-library' import { createMiddleware } from 'third-party-library'
export default createMiddleware() export default createMiddleware()
``` ```
> **Good to know**: Third-party libraries may still refer to `proxy` as `middleware`.
## More examples ## More examples
See more examples on using [Router Handlers](/docs/app/api-reference/file-conventions/route#examples) and the [`middleware`](/docs/app/api-reference/file-conventions/middleware#examples) API references. See more examples on using [Router Handlers](/docs/app/api-reference/file-conventions/route#examples) and the [`proxy`](/docs/app/api-reference/file-conventions/proxy#examples) API references.
These examples include, working with [Cookies](/docs/app/api-reference/file-conventions/route#cookies), [Headers](/docs/app/api-reference/file-conventions/route#headers), [Streaming](/docs/app/api-reference/file-conventions/route#streaming), Middleware [negative matching](/docs/app/api-reference/file-conventions/middleware#negative-matching), and other useful code snippets. These examples include, working with [Cookies](/docs/app/api-reference/file-conventions/route#cookies), [Headers](/docs/app/api-reference/file-conventions/route#headers), [Streaming](/docs/app/api-reference/file-conventions/route#streaming), Proxy [negative matching](/docs/app/api-reference/file-conventions/proxy#negative-matching), and other useful code snippets.
## Caveats ## Caveats
......
...@@ -31,7 +31,7 @@ By default, Next.js will cache as much as possible to improve performance and re ...@@ -31,7 +31,7 @@ By default, Next.js will cache as much as possible to improve performance and re
Caching behavior changes depending on whether the route is statically or dynamically rendered, data is cached or uncached, and whether a request is part of an initial visit or a subsequent navigation. Depending on your use case, you can configure the caching behavior for individual routes and data requests. Caching behavior changes depending on whether the route is statically or dynamically rendered, data is cached or uncached, and whether a request is part of an initial visit or a subsequent navigation. Depending on your use case, you can configure the caching behavior for individual routes and data requests.
Fetch caching is **not** supported in `middleware`. Any fetches done inside of your `middleware` will be uncached. Fetch caching is **not** supported in `proxy`. Any fetches done inside of your `proxy` will be uncached.
## Request Memoization ## Request Memoization
......
...@@ -4,7 +4,7 @@ nav_title: Content Security Policy ...@@ -4,7 +4,7 @@ nav_title: Content Security Policy
description: Learn how to set a Content Security Policy (CSP) for your Next.js application. description: Learn how to set a Content Security Policy (CSP) for your Next.js application.
related: related:
links: links:
- app/api-reference/file-conventions/middleware - app/api-reference/file-conventions/proxy
- app/api-reference/functions/headers - app/api-reference/functions/headers
--- ---
...@@ -31,18 +31,18 @@ CSP can block both inline and external scripts to prevent attacks. A nonce lets ...@@ -31,18 +31,18 @@ CSP can block both inline and external scripts to prevent attacks. A nonce lets
If an attacker wanted to load a script into your page, they'd need to guess the nonce value. That's why the nonce must be unpredictable and unique for every request. If an attacker wanted to load a script into your page, they'd need to guess the nonce value. That's why the nonce must be unpredictable and unique for every request.
### Adding a nonce with Middleware ### Adding a nonce with Proxy
[Middleware](/docs/app/api-reference/file-conventions/middleware) enables you to add headers and generate nonces before the page renders. [Proxy](/docs/app/api-reference/file-conventions/proxy) enables you to add headers and generate nonces before the page renders.
Every time a page is viewed, a fresh nonce should be generated. This means that you **must use [dynamic rendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering) to add nonces**. Every time a page is viewed, a fresh nonce should be generated. This means that you **must use [dynamic rendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering) to add nonces**.
For example: For example:
```ts filename="middleware.ts" switcher ```ts filename="proxy.ts" switcher
import { NextRequest, NextResponse } from 'next/server' import { NextRequest, NextResponse } from 'next/server'
export function middleware(request: NextRequest) { export function proxy(request: NextRequest) {
const nonce = Buffer.from(crypto.randomUUID()).toString('base64') const nonce = Buffer.from(crypto.randomUUID()).toString('base64')
const cspHeader = ` const cspHeader = `
default-src 'self'; default-src 'self';
...@@ -83,10 +83,10 @@ export function middleware(request: NextRequest) { ...@@ -83,10 +83,10 @@ export function middleware(request: NextRequest) {
} }
``` ```
```js filename="middleware.js" switcher ```js filename="proxy.js" switcher
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
export function middleware(request) { export function proxy(request) {
const nonce = Buffer.from(crypto.randomUUID()).toString('base64') const nonce = Buffer.from(crypto.randomUUID()).toString('base64')
const cspHeader = ` const cspHeader = `
default-src 'self'; default-src 'self';
...@@ -126,11 +126,11 @@ export function middleware(request) { ...@@ -126,11 +126,11 @@ export function middleware(request) {
} }
``` ```
By default, Middleware runs on all requests. You can filter Middleware to run on specific paths using a [`matcher`](/docs/app/api-reference/file-conventions/middleware#matcher). By default, Proxy runs on all requests. You can filter Proxy to run on specific paths using a [`matcher`](/docs/app/api-reference/file-conventions/proxy#matcher).
We recommend ignoring matching prefetches (from `next/link`) and static assets that don't need the CSP header. We recommend ignoring matching prefetches (from `next/link`) and static assets that don't need the CSP header.
```ts filename="middleware.ts" switcher ```ts filename="proxy.ts" switcher
export const config = { export const config = {
matcher: [ matcher: [
/* /*
...@@ -151,7 +151,7 @@ export const config = { ...@@ -151,7 +151,7 @@ export const config = {
} }
``` ```
```js filename="middleware.js" switcher ```js filename="proxy.js" switcher
export const config = { export const config = {
matcher: [ matcher: [
/* /*
...@@ -178,7 +178,7 @@ To use a nonce, your page must be **dynamically rendered**. This is because Next ...@@ -178,7 +178,7 @@ To use a nonce, your page must be **dynamically rendered**. This is because Next
Here’s how nonce support works in a dynamically rendered page: Here’s how nonce support works in a dynamically rendered page:
1. **Middleware generates a nonce**: Your middleware creates a unique nonce for the request, adds it to your `Content-Security-Policy` header, and also sets it in a custom `x-nonce` header. 1. **Proxy generates a nonce**: Your proxy creates a unique nonce for the request, adds it to your `Content-Security-Policy` header, and also sets it in a custom `x-nonce` header.
2. **Next.js extracts the nonce**: During rendering, Next.js parses the `Content-Security-Policy` header and extracts the nonce using the `'nonce-{value}'` pattern. 2. **Next.js extracts the nonce**: During rendering, Next.js parses the `Content-Security-Policy` header and extracts the nonce using the `'nonce-{value}'` pattern.
3. **Nonce is applied automatically**: Next.js attaches the nonce to: 3. **Nonce is applied automatically**: Next.js attaches the nonce to:
- Framework scripts (React, Next.js runtime) - Framework scripts (React, Next.js runtime)
...@@ -478,7 +478,7 @@ module.exports = nextConfig ...@@ -478,7 +478,7 @@ module.exports = nextConfig
When SRI is enabled, you can continue using your existing CSP policies. SRI works independently by adding `integrity` attributes to your assets: When SRI is enabled, you can continue using your existing CSP policies. SRI works independently by adding `integrity` attributes to your assets:
> **Good to know**: For dynamic rendering scenarios, you can still generate nonces with middleware if needed, combining both SRI integrity attributes and nonce-based CSP approaches. > **Good to know**: For dynamic rendering scenarios, you can still generate nonces with proxy if needed, combining both SRI integrity attributes and nonce-based CSP approaches.
```js filename="next.config.js" ```js filename="next.config.js"
const cspHeader = ` const cspHeader = `
...@@ -540,8 +540,8 @@ CSP implementation differs between development and production environments: ...@@ -540,8 +540,8 @@ CSP implementation differs between development and production environments:
In development, you will need to enable `'unsafe-eval'` to support APIs that provide additional debugging information: In development, you will need to enable `'unsafe-eval'` to support APIs that provide additional debugging information:
```ts filename="middleware.ts" switcher ```ts filename="proxy.ts" switcher
export function middleware(request: NextRequest) { export function proxy(request: NextRequest) {
const nonce = Buffer.from(crypto.randomUUID()).toString('base64') const nonce = Buffer.from(crypto.randomUUID()).toString('base64')
const isDev = process.env.NODE_ENV === 'development' const isDev = process.env.NODE_ENV === 'development'
...@@ -558,12 +558,12 @@ export function middleware(request: NextRequest) { ...@@ -558,12 +558,12 @@ export function middleware(request: NextRequest) {
upgrade-insecure-requests; upgrade-insecure-requests;
` `
// Rest of middleware implementation // Rest of proxy implementation
} }
``` ```
```js filename="middleware.js" switcher ```js filename="proxy.js" switcher
export function middleware(request) { export function proxy(request) {
const nonce = Buffer.from(crypto.randomUUID()).toString('base64') const nonce = Buffer.from(crypto.randomUUID()).toString('base64')
const isDev = process.env.NODE_ENV === 'development' const isDev = process.env.NODE_ENV === 'development'
...@@ -580,7 +580,7 @@ export function middleware(request) { ...@@ -580,7 +580,7 @@ export function middleware(request) {
upgrade-insecure-requests; upgrade-insecure-requests;
` `
// Rest of middleware implementation // Rest of proxy implementation
} }
``` ```
...@@ -588,7 +588,7 @@ export function middleware(request) { ...@@ -588,7 +588,7 @@ export function middleware(request) {
Common issues in production: Common issues in production:
- **Nonce not applied**: Ensure your middleware runs on all necessary routes - **Nonce not applied**: Ensure your proxy runs on all necessary routes
- **Static assets blocked**: Verify your CSP allows Next.js static assets - **Static assets blocked**: Verify your CSP allows Next.js static assets
- **Third-party scripts**: Add necessary domains to your CSP policy - **Third-party scripts**: Add necessary domains to your CSP policy
...@@ -689,7 +689,7 @@ export default function App({ Component, pageProps }) { ...@@ -689,7 +689,7 @@ export default function App({ Component, pageProps }) {
Update your CSP to allow third-party domains: Update your CSP to allow third-party domains:
```ts filename="middleware.ts" switcher ```ts filename="proxy.ts" switcher
const cspHeader = ` const cspHeader = `
default-src 'self'; default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic' https://www.googletagmanager.com; script-src 'self' 'nonce-${nonce}' 'strict-dynamic' https://www.googletagmanager.com;
...@@ -698,7 +698,7 @@ const cspHeader = ` ...@@ -698,7 +698,7 @@ const cspHeader = `
` `
``` ```
```js filename="middleware.js" switcher ```js filename="proxy.js" switcher
const cspHeader = ` const cspHeader = `
default-src 'self'; default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic' https://www.googletagmanager.com; script-src 'self' 'nonce-${nonce}' 'strict-dynamic' https://www.googletagmanager.com;
......
...@@ -471,4 +471,4 @@ If you're doing an audit of a Next.js project, here are a few things we recommen ...@@ -471,4 +471,4 @@ If you're doing an audit of a Next.js project, here are a few things we recommen
- **`"use client"` files:** Are the Component props expecting private data? Are the type signatures overly broad? - **`"use client"` files:** Are the Component props expecting private data? Are the type signatures overly broad?
- **`"use server"` files:** Are the Action arguments validated in the action or inside the Data Access Layer? Is the user re-authorized inside the action? - **`"use server"` files:** Are the Action arguments validated in the action or inside the Data Access Layer? Is the user re-authorized inside the action?
- **`/[param]/.`** Folders with brackets are user input. Are params validated? - **`/[param]/.`** Folders with brackets are user input. Are params validated?
- **`middleware.ts` and `route.ts`:** Have a lot of power. Spend extra time auditing these using traditional techniques. Perform Penetration Testing or Vulnerability Scanning regularly or in alignment with your team's software development lifecycle. - **`proxy.ts` and `route.ts`:** Have a lot of power. Spend extra time auditing these using traditional techniques. Perform Penetration Testing or Vulnerability Scanning regularly or in alignment with your team's software development lifecycle.
...@@ -574,7 +574,7 @@ This will make the Next.js server console log ISR cache hits and misses. You can ...@@ -574,7 +574,7 @@ This will make the Next.js server console log ISR cache hits and misses. You can
- ISR is not supported when creating a [Static Export](/docs/app/guides/static-exports). - ISR is not supported when creating a [Static Export](/docs/app/guides/static-exports).
- If you have multiple `fetch` requests in a statically rendered route, and each has a different `revalidate` frequency, the lowest time will be used for ISR. However, those revalidate frequencies will still be respected by the [Data Cache](/docs/app/guides/caching#data-cache). - If you have multiple `fetch` requests in a statically rendered route, and each has a different `revalidate` frequency, the lowest time will be used for ISR. However, those revalidate frequencies will still be respected by the [Data Cache](/docs/app/guides/caching#data-cache).
- If any of the `fetch` requests used on a route have a `revalidate` time of `0`, or an explicit `no-store`, the route will be [dynamically rendered](/docs/app/getting-started/partial-prerendering#dynamic-rendering). - If any of the `fetch` requests used on a route have a `revalidate` time of `0`, or an explicit `no-store`, the route will be [dynamically rendered](/docs/app/getting-started/partial-prerendering#dynamic-rendering).
- Middleware won't be executed for on-demand ISR requests, meaning any path rewrites or logic in Middleware will not be applied. Ensure you are revalidating the exact path. For example, `/post/1` instead of a rewritten `/post-1`. - Proxy won't be executed for on-demand ISR requests, meaning any path rewrites or logic in Proxy will not be applied. Ensure you are revalidating the exact path. For example, `/post/1` instead of a rewritten `/post-1`.
</AppOnly> </AppOnly>
...@@ -582,7 +582,7 @@ This will make the Next.js server console log ISR cache hits and misses. You can ...@@ -582,7 +582,7 @@ This will make the Next.js server console log ISR cache hits and misses. You can
- ISR is only supported when using the Node.js runtime (default). - ISR is only supported when using the Node.js runtime (default).
- ISR is not supported when creating a [Static Export](/docs/app/guides/static-exports). - ISR is not supported when creating a [Static Export](/docs/app/guides/static-exports).
- Middleware won't be executed for on-demand ISR requests, meaning any path rewrites or logic in Middleware will not be applied. Ensure you are revalidating the exact path. For example, `/post/1` instead of a rewritten `/post-1`. - Proxy won't be executed for on-demand ISR requests, meaning any path rewrites or logic in Proxy will not be applied. Ensure you are revalidating the exact path. For example, `/post/1` instead of a rewritten `/post-1`.
</PagesOnly> </PagesOnly>
......
...@@ -18,7 +18,7 @@ It’s recommended to use the user’s language preferences in the browser to se ...@@ -18,7 +18,7 @@ It’s recommended to use the user’s language preferences in the browser to se
For example, using the following libraries, you can look at an incoming `Request` to determine which locale to select, based on the `Headers`, locales you plan to support, and the default locale. For example, using the following libraries, you can look at an incoming `Request` to determine which locale to select, based on the `Headers`, locales you plan to support, and the default locale.
```js filename="middleware.js" ```js filename="proxy.js"
import { match } from '@formatjs/intl-localematcher' import { match } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator' import Negotiator from 'negotiator'
...@@ -30,9 +30,9 @@ let defaultLocale = 'en-US' ...@@ -30,9 +30,9 @@ let defaultLocale = 'en-US'
match(languages, locales, defaultLocale) // -> 'en-US' match(languages, locales, defaultLocale) // -> 'en-US'
``` ```
Routing can be internationalized by either the sub-path (`/fr/products`) or domain (`my-site.fr/products`). With this information, you can now redirect the user based on the locale inside [Middleware](/docs/app/api-reference/file-conventions/middleware). Routing can be internationalized by either the sub-path (`/fr/products`) or domain (`my-site.fr/products`). With this information, you can now redirect the user based on the locale inside [Proxy](/docs/app/api-reference/file-conventions/proxy).
```js filename="middleware.js" ```js filename="proxy.js"
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
let locales = ['en-US', 'nl-NL', 'nl'] let locales = ['en-US', 'nl-NL', 'nl']
...@@ -40,7 +40,7 @@ let locales = ['en-US', 'nl-NL', 'nl'] ...@@ -40,7 +40,7 @@ let locales = ['en-US', 'nl-NL', 'nl']
// Get the preferred locale, similar to the above or using a library // Get the preferred locale, similar to the above or using a library
function getLocale(request) { ... } function getLocale(request) { ... }
export function middleware(request) { export function proxy(request) {
// Check if there is any supported locale in the pathname // Check if there is any supported locale in the pathname
const { pathname } = request.nextUrl const { pathname } = request.nextUrl
const pathnameHasLocale = locales.some( const pathnameHasLocale = locales.some(
......
...@@ -37,9 +37,9 @@ This enables you to build pages that are faster to load and eliminate [layout sh ...@@ -37,9 +37,9 @@ This enables you to build pages that are faster to load and eliminate [layout sh
Depending on your needs, Next.js allows you to choose your data fetching strategy on a page or component-level basis. For example, you could fetch data from your CMS and render blog posts at build time (SSG) for quick load speeds, or fetch data at request time (SSR) when necessary. Depending on your needs, Next.js allows you to choose your data fetching strategy on a page or component-level basis. For example, you could fetch data from your CMS and render blog posts at build time (SSG) for quick load speeds, or fetch data at request time (SSR) when necessary.
### Middleware ### Proxy
[Next.js Middleware](/docs/app/api-reference/file-conventions/middleware) allows you to run code on the server before a request is completed. For instance, you can avoid a flash of unauthenticated content by redirecting a user to a login page in the middleware for authenticated-only pages. You can also use it for features like A/B testing, experimentation, and [internationalization](/docs/app/guides/internationalization). [Next.js Proxy](/docs/app/api-reference/file-conventions/proxy) allows you to run code on the server before a request is completed. For instance, you can avoid a flash of unauthenticated content by redirecting a user to a login page in the proxy for authenticated-only pages. You can also use it for features like A/B testing, experimentation, and [internationalization](/docs/app/guides/internationalization).
### Built-in Optimizations ### Built-in Optimizations
......
...@@ -37,9 +37,9 @@ This enables you to build pages that are faster to load and eliminate [layout sh ...@@ -37,9 +37,9 @@ This enables you to build pages that are faster to load and eliminate [layout sh
Depending on your needs, Next.js allows you to choose your data fetching strategy on a page and component basis. You can decide to fetch at build time, at request time on the server, or on the client. For example, you can fetch data from your CMS and render your blog posts at build time, which can then be efficiently cached on a CDN. Depending on your needs, Next.js allows you to choose your data fetching strategy on a page and component basis. You can decide to fetch at build time, at request time on the server, or on the client. For example, you can fetch data from your CMS and render your blog posts at build time, which can then be efficiently cached on a CDN.
### Middleware ### Proxy
[Next.js Middleware](/docs/app/api-reference/file-conventions/middleware) allows you to run code on the server before a request is completed. This is especially useful to avoid having a flash of unauthenticated content when the user visits an authenticated-only page by redirecting the user to a login page. The middleware is also useful for experimentation and [internationalization](/docs/app/guides/internationalization). [Next.js Proxy](/docs/app/api-reference/file-conventions/proxy) allows you to run code on the server before a request is completed. This is especially useful to avoid having a flash of unauthenticated content when the user visits an authenticated-only page by redirecting the user to a login page. The proxy is also useful for experimentation and [internationalization](/docs/app/guides/internationalization).
### Built-in Optimizations ### Built-in Optimizations
......
...@@ -98,12 +98,12 @@ async rewrites() { ...@@ -98,12 +98,12 @@ async rewrites() {
> **Good to know**: URL paths should be unique to a zone. For example, two zones trying to serve `/blog` would create a routing conflict. > **Good to know**: URL paths should be unique to a zone. For example, two zones trying to serve `/blog` would create a routing conflict.
### Routing requests using middleware ### Routing requests using proxy
Routing requests through [`rewrites`](/docs/app/api-reference/config/next-config-js/rewrites) is recommended to minimize latency overhead for the requests, but middleware can also be used when there is a need for a dynamic decision when routing. For example, if you are using a feature flag to decide where a path should be routed such as during a migration, you can use middleware. Routing requests through [`rewrites`](/docs/app/api-reference/config/next-config-js/rewrites) is recommended to minimize latency overhead for the requests, but proxy can also be used when there is a need for a dynamic decision when routing. For example, if you are using a feature flag to decide where a path should be routed such as during a migration, you can use proxy.
```js filename="middleware.js" ```js filename="proxy.js"
export async function middleware(request) { export async function proxy(request) {
const { pathname, search } = req.nextUrl; const { pathname, search } = req.nextUrl;
if (pathname === '/your-path' && myFeatureFlag.isEnabled()) { if (pathname === '/your-path' && myFeatureFlag.isEnabled()) {
return NextResponse.rewrite(`${rewriteDomain}${pathname}${search}); return NextResponse.rewrite(`${rewriteDomain}${pathname}${search});
......
This diff is collapsed.
...@@ -22,11 +22,11 @@ Image Optimization can be used with a [static export](/docs/app/guides/static-ex ...@@ -22,11 +22,11 @@ Image Optimization can be used with a [static export](/docs/app/guides/static-ex
> - Learn more about the [caching behavior of optimized images](/docs/app/api-reference/components/image#minimumcachettl) and how to configure the TTL. > - Learn more about the [caching behavior of optimized images](/docs/app/api-reference/components/image#minimumcachettl) and how to configure the TTL.
> - You can also [disable Image Optimization](/docs/app/api-reference/components/image#unoptimized) and still retain other benefits of using `next/image` if you prefer. For example, if you are optimizing images yourself separately. > - You can also [disable Image Optimization](/docs/app/api-reference/components/image#unoptimized) and still retain other benefits of using `next/image` if you prefer. For example, if you are optimizing images yourself separately.
## Middleware ## Proxy
[Middleware](/docs/app/api-reference/file-conventions/middleware) works self-hosted with zero configuration when deploying using `next start`. Since it requires access to the incoming request, it is not supported when using a [static export](/docs/app/guides/static-exports). [Proxy](/docs/app/api-reference/file-conventions/proxy) works self-hosted with zero configuration when deploying using `next start`. Since it requires access to the incoming request, it is not supported when using a [static export](/docs/app/guides/static-exports).
Middleware uses the [Edge runtime](/docs/app/api-reference/edge), a subset of all available Node.js APIs to help ensure low latency, since it may run in front of every route or asset in your application. If you do not want this, you can use the [full Node.js runtime](/blog/next-15-2#nodejs-middleware-experimental) to run Middleware. Proxy uses the [Edge runtime](/docs/app/api-reference/edge), a subset of all available Node.js APIs to help ensure low latency, since it may run in front of every route or asset in your application. If you do not want this, you can use the [full Node.js runtime](/blog/next-15-2#nodejs-middleware-experimental) to run Proxy.
If you are looking to add logic (or use an external package) that requires all Node.js APIs, you might be able to move this logic to a [layout](/docs/app/api-reference/file-conventions/layout) as a [Server Component](/docs/app/getting-started/server-and-client-components). For example, checking [headers](/docs/app/api-reference/functions/headers) and [redirecting](/docs/app/api-reference/functions/redirect). You can also use headers, cookies, or query parameters to [redirect](/docs/app/api-reference/config/next-config-js/redirects#header-cookie-and-query-matching) or [rewrite](/docs/app/api-reference/config/next-config-js/rewrites#header-cookie-and-query-matching) through `next.config.js`. If that does not work, you can also use a [custom server](/docs/pages/guides/custom-server). If you are looking to add logic (or use an external package) that requires all Node.js APIs, you might be able to move this logic to a [layout](/docs/app/api-reference/file-conventions/layout) as a [Server Component](/docs/app/getting-started/server-and-client-components). For example, checking [headers](/docs/app/api-reference/functions/headers) and [redirecting](/docs/app/api-reference/functions/redirect). You can also use headers, cookies, or query parameters to [redirect](/docs/app/api-reference/config/next-config-js/redirects#header-cookie-and-query-matching) or [rewrite](/docs/app/api-reference/config/next-config-js/rewrites#header-cookie-and-query-matching) through `next.config.js`. If that does not work, you can also use a [custom server](/docs/pages/guides/custom-server).
......
...@@ -284,7 +284,7 @@ Features that require a Node.js server, or dynamic logic that cannot be computed ...@@ -284,7 +284,7 @@ Features that require a Node.js server, or dynamic logic that cannot be computed
- [Rewrites](/docs/app/api-reference/config/next-config-js/rewrites) - [Rewrites](/docs/app/api-reference/config/next-config-js/rewrites)
- [Redirects](/docs/app/api-reference/config/next-config-js/redirects) - [Redirects](/docs/app/api-reference/config/next-config-js/redirects)
- [Headers](/docs/app/api-reference/config/next-config-js/headers) - [Headers](/docs/app/api-reference/config/next-config-js/headers)
- [Middleware](/docs/app/api-reference/file-conventions/middleware) - [Proxy](/docs/app/api-reference/file-conventions/proxy)
- [Incremental Static Regeneration](/docs/app/guides/incremental-static-regeneration) - [Incremental Static Regeneration](/docs/app/guides/incremental-static-regeneration)
- [Image Optimization](/docs/app/api-reference/components/image) with the default `loader` - [Image Optimization](/docs/app/api-reference/components/image) with the default `loader`
- [Draft Mode](/docs/app/guides/draft-mode) - [Draft Mode](/docs/app/guides/draft-mode)
...@@ -306,7 +306,7 @@ export const dynamic = 'error' ...@@ -306,7 +306,7 @@ export const dynamic = 'error'
- [Rewrites](/docs/pages/api-reference/config/next-config-js/rewrites) - [Rewrites](/docs/pages/api-reference/config/next-config-js/rewrites)
- [Redirects](/docs/pages/api-reference/config/next-config-js/redirects) - [Redirects](/docs/pages/api-reference/config/next-config-js/redirects)
- [Headers](/docs/pages/api-reference/config/next-config-js/headers) - [Headers](/docs/pages/api-reference/config/next-config-js/headers)
- [Middleware](/docs/pages/api-reference/file-conventions/middleware) - [Proxy](/docs/pages/api-reference/file-conventions/proxy)
- [Incremental Static Regeneration](/docs/pages/guides/incremental-static-regeneration) - [Incremental Static Regeneration](/docs/pages/guides/incremental-static-regeneration)
- [Image Optimization](/docs/pages/api-reference/components/image) with the default `loader` - [Image Optimization](/docs/pages/api-reference/components/image) with the default `loader`
- [Draft Mode](/docs/pages/guides/draft-mode) - [Draft Mode](/docs/pages/guides/draft-mode)
......
...@@ -884,16 +884,16 @@ export default function Home() { ...@@ -884,16 +884,16 @@ export default function Home() {
</PagesOnly> </PagesOnly>
### Prefetching links in Middleware ### Prefetching links in Proxy
It's common to use [Middleware](/docs/app/api-reference/file-conventions/middleware) for authentication or other purposes that involve rewriting the user to a different page. In order for the `<Link />` component to properly prefetch links with rewrites via Middleware, you need to tell Next.js both the URL to display and the URL to prefetch. This is required to avoid un-necessary fetches to middleware to know the correct route to prefetch. It's common to use [Proxy](/docs/app/api-reference/file-conventions/proxy) for authentication or other purposes that involve rewriting the user to a different page. In order for the `<Link />` component to properly prefetch links with rewrites via Proxy, you need to tell Next.js both the URL to display and the URL to prefetch. This is required to avoid un-necessary fetches to proxy to know the correct route to prefetch.
For example, if you want to serve a `/dashboard` route that has authenticated and visitor views, you can add the following in your Middleware to redirect the user to the correct page: For example, if you want to serve a `/dashboard` route that has authenticated and visitor views, you can add the following in your Proxy to redirect the user to the correct page:
```ts filename="middleware.ts" switcher ```ts filename="proxy.ts" switcher
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
export function middleware(request: Request) { export function proxy(request: Request) {
const nextUrl = request.nextUrl const nextUrl = request.nextUrl
if (nextUrl.pathname === '/dashboard') { if (nextUrl.pathname === '/dashboard') {
if (request.cookies.authToken) { if (request.cookies.authToken) {
...@@ -905,10 +905,10 @@ export function middleware(request: Request) { ...@@ -905,10 +905,10 @@ export function middleware(request: Request) {
} }
``` ```
```js filename="middleware.js" switcher ```js filename="proxy.js" switcher
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
export function middleware(request) { export function proxy(request) {
const nextUrl = request.nextUrl const nextUrl = request.nextUrl
if (nextUrl.pathname === '/dashboard') { if (nextUrl.pathname === '/dashboard') {
if (request.cookies.authToken) { if (request.cookies.authToken) {
...@@ -996,7 +996,7 @@ export default function Home() { ...@@ -996,7 +996,7 @@ export default function Home() {
} }
``` ```
> **Good to know**: If you're using [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes#convention), you'll need to adapt your `as` and `href` props. For example, if you have a Dynamic Route like `/dashboard/authed/[user]` that you want to present differently via middleware, you would write: `<Link href={{ pathname: '/dashboard/authed/[user]', query: { user: username } }} as="/dashboard/[user]">Profile</Link>`. > **Good to know**: If you're using [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes#convention), you'll need to adapt your `as` and `href` props. For example, if you have a Dynamic Route like `/dashboard/authed/[user]` that you want to present differently via proxy, you would write: `<Link href={{ pathname: '/dashboard/authed/[user]', query: { user: username } }} as="/dashboard/[user]">Profile</Link>`.
</PagesOnly> </PagesOnly>
......
...@@ -13,4 +13,4 @@ Once a file is defined, Next.js will automatically serve the file (with hashes i ...@@ -13,4 +13,4 @@ Once a file is defined, Next.js will automatically serve the file (with hashes i
> **Good to know**: > **Good to know**:
> >
> - Special Route Handlers like [`sitemap.ts`](/docs/app/api-reference/file-conventions/metadata/sitemap), [`opengraph-image.tsx`](/docs/app/api-reference/file-conventions/metadata/opengraph-image), and [`icon.tsx`](/docs/app/api-reference/file-conventions/metadata/app-icons), and other [metadata files](/docs/app/api-reference/file-conventions/metadata) are cached by default. > - Special Route Handlers like [`sitemap.ts`](/docs/app/api-reference/file-conventions/metadata/sitemap), [`opengraph-image.tsx`](/docs/app/api-reference/file-conventions/metadata/opengraph-image), and [`icon.tsx`](/docs/app/api-reference/file-conventions/metadata/app-icons), and other [metadata files](/docs/app/api-reference/file-conventions/metadata) are cached by default.
> - If using along with [`middleware.ts`](/docs/app/api-reference/file-conventions/middleware), [configure the matcher](/docs/app/api-reference/file-conventions/middleware#matcher) to exclude the metadata files. > - If using along with [`proxy.ts`](/docs/app/api-reference/file-conventions/proxy), [configure the matcher](/docs/app/api-reference/file-conventions/proxy#matcher) to exclude the metadata files.
...@@ -101,7 +101,7 @@ Some crawlers may label these responses as “soft 404s”. In the streaming cas ...@@ -101,7 +101,7 @@ Some crawlers may label these responses as “soft 404s”. In the streaming cas
If you need a 404 status, for compliance or analytics, ensure the resource exists before the response body is streamed, so that the server can set the HTTP status code. If you need a 404 status, for compliance or analytics, ensure the resource exists before the response body is streamed, so that the server can set the HTTP status code.
You can run this check in [`middleware`](/docs/app/api-reference/file-conventions/middleware) to rewrite missing slugs to a not-found route, or [produce a 404 response](/docs/app/api-reference/file-conventions/middleware#producing-a-response). Keep middleware checks fast, and avoid fetching full content there. You can run this check in [`proxy`](/docs/app/api-reference/file-conventions/proxy) to rewrite missing slugs to a not-found route, or [produce a 404 response](/docs/app/api-reference/file-conventions/proxy#producing-a-response). Keep proxy checks fast, and avoid fetching full content there.
<details> <details>
<summary>When is the response body streamed?</summary> <summary>When is the response body streamed?</summary>
......
...@@ -8,6 +8,8 @@ related: ...@@ -8,6 +8,8 @@ related:
- app/api-reference/functions/next-response - app/api-reference/functions/next-response
--- ---
> **Note**: The `middleware` file convention is deprecated and has been renamed to `proxy`. See [Migration to Proxy](#migration-to-proxy) for more details.
The `proxy.js|ts` file is used to write [Proxy](/docs/app/getting-started/proxy) 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 `proxy.js|ts` file is used to write [Proxy](/docs/app/getting-started/proxy) 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.
Proxy executes before routes are rendered. It's particularly useful for implementing custom server-side logic like authentication, logging, or handling redirects. Proxy executes before routes are rendered. It's particularly useful for implementing custom server-side logic like authentication, logging, or handling redirects.
...@@ -684,6 +686,39 @@ expect(getRewrittenUrl(response)).toEqual('https://other-domain.com/docs') ...@@ -684,6 +686,39 @@ expect(getRewrittenUrl(response)).toEqual('https://other-domain.com/docs')
Learn how to [configure Proxy](/docs/app/guides/self-hosting#proxy) when self-hosting Next.js. Learn how to [configure Proxy](/docs/app/guides/self-hosting#proxy) when self-hosting Next.js.
## Migration to Proxy
### Why the Change
The reason behind the renaming of `middleware` is that the term "middleware can often be confused with Express.js middleware, leading to a misinterpretation of its purpose. Also, Middleware is highly capable, so it may encourage the usage; however, this feature is recommended to be used as a last resort.
Next.js is moving forward to provide better APIs with better ergonomics so that developers can achieve their goals without Middleware. This is the reason behind the renaming of `middleware`.
### Why "Proxy"
The name Proxy clarifies what Middleware is capable of. The term "proxy" implies that it has a network boundary in front of the app, which is the behavior of Middleware. Also, Middleware defaults to run at the [Edge Runtime](/docs/app/api-reference/edge), which can run closer to the client, separated from the app's region. These behaviors align better with the term "proxy" and provide a clearer purpose of the feature.
### How to Migrate
We recommend users avoid relying on Middleware unless no other options exist. Our goal is to give them APIs with better ergonomics so they can achieve their goals without Middleware.
The term “middleware” often confuses users with Express.js middleware, which can encourage misuse. To clarify our direction, we are renaming the file convention to “proxy.” This highlights that we are moving away from Middleware, breaking down its overloaded features, and making the Proxy clear in its purpose.
Next.js provides a codemod to migrate from `middleware.ts` to `proxy.ts`. You can run the following command to migrate:
```bash
npx @next/codemod@canary middleware-to-proxy .
```
The codemod will rename the file and the function name from `middleware` to `proxy`.
```diff
// middleware.ts -> proxy.ts
- export function middleware() {
+ export function proxy() {
```
## Version history ## Version history
| Version | Changes | | Version | Changes |
......
...@@ -162,7 +162,7 @@ export const fetchCache = 'auto' ...@@ -162,7 +162,7 @@ export const fetchCache = 'auto'
### `runtime` ### `runtime`
We recommend using the Node.js runtime for rendering your application, and the Edge runtime for Middleware. We recommend using the Node.js runtime for rendering your application, and the Edge runtime for Proxy.
```tsx filename="layout.tsx | page.tsx | route.ts" switcher ```tsx filename="layout.tsx | page.tsx | route.ts" switcher
export const runtime = 'nodejs' export const runtime = 'nodejs'
......
...@@ -546,7 +546,7 @@ export async function GET(request) { ...@@ -546,7 +546,7 @@ export async function GET(request) {
> **Good to know**: > **Good to know**:
> >
> - To add CORS headers to multiple Route Handlers, you can use [Middleware](/docs/app/api-reference/file-conventions/middleware#cors) or the [`next.config.js` file](/docs/app/api-reference/config/next-config-js/headers#cors). > - To add CORS headers to multiple Route Handlers, you can use [Proxy](/docs/app/api-reference/file-conventions/proxy#cors) or the [`next.config.js` file](/docs/app/api-reference/config/next-config-js/headers#cors).
### Webhooks ### Webhooks
......
...@@ -30,6 +30,6 @@ To use the `src` folder, move the `app` Router folder or `pages` Router folder t ...@@ -30,6 +30,6 @@ To use the `src` folder, move the `app` Router folder or `pages` Router folder t
> - `.env.*` files should remain in the root of your project. > - `.env.*` files should remain in the root of your project.
> - `src/app` or `src/pages` will be ignored if `app` or `pages` are present in the root directory. > - `src/app` or `src/pages` will be ignored if `app` or `pages` are present in the root directory.
> - If you're using `src`, you'll probably also move other application folders such as `/components` or `/lib`. > - If you're using `src`, you'll probably also move other application folders such as `/components` or `/lib`.
> - If you're using Middleware, ensure it is placed inside the `src` folder. > - If you're using Proxy, ensure it is placed inside the `src` folder.
> - If you're using Tailwind CSS, you'll need to add the `/src` prefix to the `tailwind.config.js` file in the [content section](https://tailwindcss.com/docs/content-configuration). > - If you're using Tailwind CSS, you'll need to add the `/src` prefix to the `tailwind.config.js` file in the [content section](https://tailwindcss.com/docs/content-configuration).
> - If you are using TypeScript paths for imports such as `@/*`, you should update the `paths` object in `tsconfig.json` to include `src/`. > - If you are using TypeScript paths for imports such as `@/*`, you should update the `paths` object in `tsconfig.json` to include `src/`.
...@@ -5,7 +5,7 @@ description: API Reference for the after function. ...@@ -5,7 +5,7 @@ description: API Reference for the after function.
`after` allows you to schedule work to be executed after a response (or prerender) is finished. This is useful for tasks and other side effects that should not block the response, such as logging and analytics. `after` allows you to schedule work to be executed after a response (or prerender) is finished. This is useful for tasks and other side effects that should not block the response, such as logging and analytics.
It can be used in [Server Components](/docs/app/getting-started/server-and-client-components) (including [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata)), [Server Actions](/docs/app/getting-started/updating-data), [Route Handlers](/docs/app/api-reference/file-conventions/route), and [Middleware](/docs/app/api-reference/file-conventions/middleware). It can be used in [Server Components](/docs/app/getting-started/server-and-client-components) (including [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata)), [Server Actions](/docs/app/getting-started/updating-data), [Route Handlers](/docs/app/api-reference/file-conventions/route), and [Proxy](/docs/app/api-reference/file-conventions/proxy).
The function accepts a callback that will be executed after the response (or prerender) is finished: The function accepts a callback that will be executed after the response (or prerender) is finished:
......
...@@ -1067,17 +1067,17 @@ export const metadata = { ...@@ -1067,17 +1067,17 @@ export const metadata = {
The following metadata types do not currently have built-in support. However, they can still be rendered in the layout or page itself. The following metadata types do not currently have built-in support. However, they can still be rendered in the layout or page itself.
| Metadata | Recommendation | | Metadata | Recommendation |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `<meta http-equiv="...">` | Use appropriate HTTP Headers via [`redirect()`](/docs/app/api-reference/functions/redirect), [Middleware](/docs/app/api-reference/file-conventions/middleware#nextresponse), [Security Headers](/docs/app/api-reference/config/next-config-js/headers) | | `<meta http-equiv="...">` | Use appropriate HTTP Headers via [`redirect()`](/docs/app/api-reference/functions/redirect), [Proxy](/docs/app/api-reference/file-conventions/proxy#nextresponse), [Security Headers](/docs/app/api-reference/config/next-config-js/headers) |
| `<base>` | Render the tag in the layout or page itself. | | `<base>` | Render the tag in the layout or page itself. |
| `<noscript>` | Render the tag in the layout or page itself. | | `<noscript>` | Render the tag in the layout or page itself. |
| `<style>` | Learn more about [styling in Next.js](/docs/app/getting-started/css). | | `<style>` | Learn more about [styling in Next.js](/docs/app/getting-started/css). |
| `<script>` | Learn more about [using scripts](/docs/app/guides/scripts). | | `<script>` | Learn more about [using scripts](/docs/app/guides/scripts). |
| `<link rel="stylesheet" />` | `import` stylesheets directly in the layout or page itself. | | `<link rel="stylesheet" />` | `import` stylesheets directly in the layout or page itself. |
| `<link rel="preload />` | Use [ReactDOM preload method](#link-relpreload) | | `<link rel="preload />` | Use [ReactDOM preload method](#link-relpreload) |
| `<link rel="preconnect" />` | Use [ReactDOM preconnect method](#link-relpreconnect) | | `<link rel="preconnect" />` | Use [ReactDOM preconnect method](#link-relpreconnect) |
| `<link rel="dns-prefetch" />` | Use [ReactDOM prefetchDNS method](#link-reldns-prefetch) | | `<link rel="dns-prefetch" />` | Use [ReactDOM prefetchDNS method](#link-reldns-prefetch) |
### Resource hints ### Resource hints
......
...@@ -119,7 +119,7 @@ return NextResponse.rewrite(new URL('/proxy', request.url)) ...@@ -119,7 +119,7 @@ return NextResponse.rewrite(new URL('/proxy', request.url))
## `next()` ## `next()`
The `next()` method is useful for Middleware, as it allows you to return early and continue routing. The `next()` method is useful for Proxy, as it allows you to return early and continue routing.
```ts ```ts
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
...@@ -147,12 +147,12 @@ return NextResponse.next({ ...@@ -147,12 +147,12 @@ return NextResponse.next({
This forwards `newHeaders` upstream to the target page, route, or server action, and does not expose them to the client. While this pattern is useful for passing data upstream, it should be used with caution because the headers containing this data may be forwarded to external services. This forwards `newHeaders` upstream to the target page, route, or server action, and does not expose them to the client. While this pattern is useful for passing data upstream, it should be used with caution because the headers containing this data may be forwarded to external services.
In contrast, `NextResponse.next({ headers })` is a shorthand for sending headers from middleware to the client. This is **NOT** good practice and should be avoided. Among other reasons because setting response headers like `Content-Type`, can override framework expectations (for example, the `Content-Type` used by Server Actions), leading to failed submissions or broken streaming responses. In contrast, `NextResponse.next({ headers })` is a shorthand for sending headers from proxy to the client. This is **NOT** good practice and should be avoided. Among other reasons because setting response headers like `Content-Type`, can override framework expectations (for example, the `Content-Type` used by Server Actions), leading to failed submissions or broken streaming responses.
```ts ```ts
import { type NextRequest, NextResponse } from 'next/server' import { type NextRequest, NextResponse } from 'next/server'
async function middleware(request: NextRequest) { async function proxy(request: NextRequest) {
const headers = await injectAuth(request.headers) const headers = await injectAuth(request.headers)
// DO NOT forward headers like this // DO NOT forward headers like this
return NextResponse.next({ headers }) return NextResponse.next({ headers })
...@@ -166,7 +166,7 @@ Prefer a defensive approach by creating a subset of incoming request headers usi ...@@ -166,7 +166,7 @@ Prefer a defensive approach by creating a subset of incoming request headers usi
```ts ```ts
import { type NextRequest, NextResponse } from 'next/server' import { type NextRequest, NextResponse } from 'next/server'
function middleware(request: NextRequest) { function proxy(request: NextRequest) {
const incoming = new Headers(request.headers) const incoming = new Headers(request.headers)
const forwarded = new Headers() const forwarded = new Headers()
......
...@@ -52,7 +52,7 @@ The `type` parameter has no effect when used in Server Components. ...@@ -52,7 +52,7 @@ The `type` parameter has no effect when used in Server Components.
- `redirect` throws an error so it should be called **outside** the `try` block when using `try/catch` statements. - `redirect` throws an error so it should be called **outside** the `try` block when using `try/catch` statements.
- `redirect` can be called in Client Components during the rendering process but not in event handlers. You can use the [`useRouter` hook](/docs/app/api-reference/functions/use-router) instead. - `redirect` can be called in Client Components during the rendering process but not in event handlers. You can use the [`useRouter` hook](/docs/app/api-reference/functions/use-router) instead.
- `redirect` also accepts absolute URLs and can be used to redirect to external links. - `redirect` also accepts absolute URLs and can be used to redirect to external links.
- If you'd like to redirect before the render process, use [`next.config.js`](/docs/app/guides/redirecting#redirects-in-nextconfigjs) or [Middleware](/docs/app/guides/redirecting#nextresponseredirect-in-middleware). - If you'd like to redirect before the render process, use [`next.config.js`](/docs/app/guides/redirecting#redirects-in-nextconfigjs) or [Proxy](/docs/app/guides/redirecting#nextresponseredirect-in-proxy).
## Example ## Example
......
...@@ -9,7 +9,7 @@ description: API Reference for the revalidatePath function. ...@@ -9,7 +9,7 @@ description: API Reference for the revalidatePath function.
`revalidatePath` can be called in Server Functions and Route Handlers. `revalidatePath` can be called in Server Functions and Route Handlers.
`revalidatePath` cannot be called in Client Components or Middleware, as it only works in server environments. `revalidatePath` cannot be called in Client Components or Proxy, as it only works in server environments.
> **Good to know**: > **Good to know**:
> >
......
...@@ -11,7 +11,7 @@ This function is ideal for content where a slight delay in updates is acceptable ...@@ -11,7 +11,7 @@ This function is ideal for content where a slight delay in updates is acceptable
`revalidateTag` can be called in Server Functions and Route Handlers. `revalidateTag` can be called in Server Functions and Route Handlers.
`revalidateTag` cannot be called in Client Components or Middleware, as it only works in server environments. `revalidateTag` cannot be called in Client Components or Proxy, as it only works in server environments.
### Revalidation Behavior ### Revalidation Behavior
......
...@@ -36,7 +36,7 @@ For example, a Client Component with `usePathname` will be rendered into HTML on ...@@ -36,7 +36,7 @@ For example, a Client Component with `usePathname` will be rendered into HTML on
> - Reading the current URL from a [Server Component](/docs/app/getting-started/server-and-client-components) is not supported. This design is intentional to support layout state being preserved across page navigations. > - Reading the current URL from a [Server Component](/docs/app/getting-started/server-and-client-components) is not supported. This design is intentional to support layout state being preserved across page navigations.
> - Compatibility mode: > - Compatibility mode:
> - `usePathname` can return `null` when a [fallback route](/docs/pages/api-reference/functions/get-static-paths#fallback-true) is being rendered or when a `pages` directory page has been [automatically statically optimized](/docs/pages/building-your-application/rendering/automatic-static-optimization) by Next.js and the router is not ready. > - `usePathname` can return `null` when a [fallback route](/docs/pages/api-reference/functions/get-static-paths#fallback-true) is being rendered or when a `pages` directory page has been [automatically statically optimized](/docs/pages/building-your-application/rendering/automatic-static-optimization) by Next.js and the router is not ready.
> - When using `usePathname` with rewrites in [`next.config`](/docs/app/api-reference/config/next-config-js/rewrites) or [`Middleware`](/docs/app/api-reference/file-conventions/middleware), `useState` and `useEffect` must also be used in order to avoid hydration mismatch errors. > - When using `usePathname` with rewrites in [`next.config`](/docs/app/api-reference/config/next-config-js/rewrites) or [`Proxy`](/docs/app/api-reference/file-conventions/proxy), `useState` and `useEffect` must also be used in order to avoid hydration mismatch errors.
> - Next.js will automatically update your types if it detects both an `app` and `pages` directory in your project. > - Next.js will automatically update your types if it detects both an `app` and `pages` directory in your project.
## Parameters ## Parameters
...@@ -94,7 +94,7 @@ function ExampleClientComponent() { ...@@ -94,7 +94,7 @@ function ExampleClientComponent() {
### Avoid hydration mismatch with rewrites ### Avoid hydration mismatch with rewrites
When a page is pre-rendered, the HTML is generated for the source pathname. If the page is then reached through a rewrite using `next.config` or `Middleware`, the browser URL may differ, and `usePathname()` will read the rewritten pathname on the client. When a page is pre-rendered, the HTML is generated for the source pathname. If the page is then reached through a rewrite using `next.config` or `Proxy`, the browser URL may differ, and `usePathname()` will read the rewritten pathname on the client.
To avoid hydration mismatches, design the UI so that only a small, isolated part depends on the client pathname. Render a stable fallback on the server and update that part after mount. To avoid hydration mismatches, design the UI so that only a small, isolated part depends on the client pathname. Render a stable fallback on the server and update that part after mount.
......
...@@ -7,10 +7,10 @@ description: The userAgent helper extends the Web Request API with additional pr ...@@ -7,10 +7,10 @@ description: The userAgent helper extends the Web Request API with additional pr
The `userAgent` helper extends the [Web Request API](https://developer.mozilla.org/docs/Web/API/Request) with additional properties and methods to interact with the user agent object from the request. The `userAgent` helper extends the [Web Request API](https://developer.mozilla.org/docs/Web/API/Request) with additional properties and methods to interact with the user agent object from the request.
```ts filename="middleware.ts" switcher ```ts filename="proxy.ts" switcher
import { NextRequest, NextResponse, userAgent } from 'next/server' import { NextRequest, NextResponse, userAgent } from 'next/server'
export function middleware(request: NextRequest) { export function proxy(request: NextRequest) {
const url = request.nextUrl const url = request.nextUrl
const { device } = userAgent(request) const { device } = userAgent(request)
...@@ -23,10 +23,10 @@ export function middleware(request: NextRequest) { ...@@ -23,10 +23,10 @@ export function middleware(request: NextRequest) {
} }
``` ```
```js filename="middleware.js" switcher ```js filename="proxy.js" switcher
import { NextResponse, userAgent } from 'next/server' import { NextResponse, userAgent } from 'next/server'
export function middleware(request) { export function proxy(request) {
const url = request.nextUrl const url = request.nextUrl
const { device } = userAgent(request) const { device } = userAgent(request)
......
...@@ -125,7 +125,7 @@ Starting in Next.js 15.1, the `next/experimental/testing/server` package contain ...@@ -125,7 +125,7 @@ Starting in Next.js 15.1, the `next/experimental/testing/server` package contain
The `unstable_getResponseFromNextConfig` function runs the [`headers`](/docs/app/api-reference/config/next-config-js/headers), [`redirects`](/docs/app/api-reference/config/next-config-js/redirects), and [`rewrites`](/docs/app/api-reference/config/next-config-js/rewrites) functions from `next.config.js` with the provided request information and returns `NextResponse` with the results of the routing. The `unstable_getResponseFromNextConfig` function runs the [`headers`](/docs/app/api-reference/config/next-config-js/headers), [`redirects`](/docs/app/api-reference/config/next-config-js/redirects), and [`rewrites`](/docs/app/api-reference/config/next-config-js/rewrites) functions from `next.config.js` with the provided request information and returns `NextResponse` with the results of the routing.
> The response from `unstable_getResponseFromNextConfig` only considers `next.config.js` fields and does not consider middleware or filesystem routes, so the result in production may be different than the unit test. > The response from `unstable_getResponseFromNextConfig` only considers `next.config.js` fields and does not consider proxy or filesystem routes, so the result in production may be different than the unit test.
```js ```js
import { import {
......
...@@ -34,13 +34,13 @@ module.exports = { ...@@ -34,13 +34,13 @@ module.exports = {
Changing these values affects _all_ Next.js pages, including the following: Changing these values affects _all_ Next.js pages, including the following:
- [`middleware.js`](/docs/pages/api-reference/file-conventions/middleware) - [`proxy.js`](/docs/pages/api-reference/file-conventions/proxy)
- [`instrumentation.js`](/docs/pages/guides/instrumentation) - [`instrumentation.js`](/docs/pages/guides/instrumentation)
- `pages/_document.js` - `pages/_document.js`
- `pages/_app.js` - `pages/_app.js`
- `pages/api/` - `pages/api/`
For example, if you reconfigure `.ts` page extensions to `.page.ts`, you would need to rename pages like `middleware.page.ts`, `instrumentation.page.ts`, `_app.page.ts`. For example, if you reconfigure `.ts` page extensions to `.page.ts`, you would need to rename pages like `proxy.page.ts`, `instrumentation.page.ts`, `_app.page.ts`.
## Including non-page files in the `pages` directory ## Including non-page files in the `pages` directory
......
--- ---
title: experimental.middlewareClientMaxBodySize title: experimental.proxyClientMaxBodySize
description: Configure the maximum request body size when using middleware. description: Configure the maximum request body size when using proxy.
version: experimental version: experimental
--- ---
When middleware is used, Next.js automatically clones the request body and buffers it in memory to enable multiple reads - both in middleware and the underlying route handler. To prevent excessive memory usage, this configuration option sets a size limit on the buffered body. When proxy is used, Next.js automatically clones the request body and buffers it in memory to enable multiple reads - both in proxy and the underlying route handler. To prevent excessive memory usage, this configuration option sets a size limit on the buffered body.
By default, the maximum body size is **10MB**. If a request body exceeds this limit, the body will only be buffered up to the limit, and a warning will be logged indicating which route exceeded the limit. By default, the maximum body size is **10MB**. If a request body exceeds this limit, the body will only be buffered up to the limit, and a warning will be logged indicating which route exceeded the limit.
...@@ -19,7 +19,7 @@ import type { NextConfig } from 'next' ...@@ -19,7 +19,7 @@ import type { NextConfig } from 'next'
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
experimental: { experimental: {
middlewareClientMaxBodySize: '1mb', proxyClientMaxBodySize: '1mb',
}, },
} }
...@@ -30,7 +30,7 @@ export default nextConfig ...@@ -30,7 +30,7 @@ export default nextConfig
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
experimental: { experimental: {
middlewareClientMaxBodySize: '1mb', proxyClientMaxBodySize: '1mb',
}, },
} }
...@@ -48,7 +48,7 @@ import type { NextConfig } from 'next' ...@@ -48,7 +48,7 @@ import type { NextConfig } from 'next'
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
experimental: { experimental: {
middlewareClientMaxBodySize: 1048576, // 1MB in bytes proxyClientMaxBodySize: 1048576, // 1MB in bytes
}, },
} }
...@@ -59,7 +59,7 @@ export default nextConfig ...@@ -59,7 +59,7 @@ export default nextConfig
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
experimental: { experimental: {
middlewareClientMaxBodySize: 1048576, // 1MB in bytes proxyClientMaxBodySize: 1048576, // 1MB in bytes
}, },
} }
...@@ -77,17 +77,17 @@ When a request body exceeds the configured limit: ...@@ -77,17 +77,17 @@ When a request body exceeds the configured limit:
If your application needs to process the full request body, you should either: If your application needs to process the full request body, you should either:
- Increase the `middlewareClientMaxBodySize` limit - Increase the `proxyClientMaxBodySize` limit
- Handle the partial body gracefully in your application logic - Handle the partial body gracefully in your application logic
## Example ## Example
```ts filename="middleware.ts" ```ts filename="proxy.ts"
import { NextRequest, NextResponse } from 'next/server' import { NextRequest, NextResponse } from 'next/server'
export async function middleware(request: NextRequest) { export async function proxy(request: NextRequest) {
// Next.js automatically buffers the body with the configured size limit // Next.js automatically buffers the body with the configured size limit
// You can read the body in middleware... // You can read the body in proxy...
const body = await request.text() const body = await request.text()
// If the body exceeded the limit, only partial data will be available // If the body exceeded the limit, only partial data will be available
...@@ -112,7 +112,7 @@ export async function POST(request: NextRequest) { ...@@ -112,7 +112,7 @@ export async function POST(request: NextRequest) {
## Good to know ## Good to know
- This setting only applies when middleware is used in your application - This setting only applies when proxy is used in your application
- The default limit of 10MB is designed to balance memory usage and typical use cases - The default limit of 10MB is designed to balance memory usage and typical use cases
- The limit applies per-request, not globally across all concurrent requests - The limit applies per-request, not globally across all concurrent requests
- For applications handling large file uploads, consider increasing the limit accordingly - For applications handling large file uploads, consider increasing the limit accordingly
...@@ -38,7 +38,7 @@ module.exports = { ...@@ -38,7 +38,7 @@ module.exports = {
Redirects are checked before the filesystem which includes pages and `/public` files. Redirects are checked before the filesystem which includes pages and `/public` files.
When using the Pages Router, redirects are not applied to client-side routing (`Link`, `router.push`) unless [Middleware](/docs/app/api-reference/file-conventions/middleware) is present and matches the path. When using the Pages Router, redirects are not applied to client-side routing (`Link`, `router.push`) unless [Proxy](/docs/app/api-reference/file-conventions/proxy) is present and matches the path.
When a redirect is applied, any query values provided in the request will be passed through to the redirect destination. For example, see the following redirect configuration: When a redirect is applied, any query values provided in the request will be passed through to the redirect destination. For example, see the following redirect configuration:
...@@ -252,7 +252,7 @@ module.exports = { ...@@ -252,7 +252,7 @@ module.exports = {
When implementing redirects with internationalization in the App Router, you can include locales in `next.config.js` redirects, but only as hardcoded paths. When implementing redirects with internationalization in the App Router, you can include locales in `next.config.js` redirects, but only as hardcoded paths.
For dynamic or per-request locale handling, use [dynamic route segments and middleware](/docs/app/guides/internationalization), which can redirect based on the user's preferred language. For dynamic or per-request locale handling, use [dynamic route segments and proxy](/docs/app/guides/internationalization), which can redirect based on the user's preferred language.
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
......
...@@ -90,7 +90,7 @@ The order Next.js routes are checked is: ...@@ -90,7 +90,7 @@ The order Next.js routes are checked is:
1. [headers](/docs/app/api-reference/config/next-config-js/headers) are checked/applied 1. [headers](/docs/app/api-reference/config/next-config-js/headers) are checked/applied
2. [redirects](/docs/app/api-reference/config/next-config-js/redirects) are checked/applied 2. [redirects](/docs/app/api-reference/config/next-config-js/redirects) are checked/applied
3. [middleware](/docs/app/api-reference/file-conventions/middleware) 3. [proxy](/docs/app/api-reference/file-conventions/proxy)
4. `beforeFiles` rewrites are checked/applied 4. `beforeFiles` rewrites are checked/applied
5. static files from the [public directory](/docs/app/api-reference/file-conventions/public-folder), `_next/static` files, and non-dynamic pages are checked/served 5. static files from the [public directory](/docs/app/api-reference/file-conventions/public-folder), `_next/static` files, and non-dynamic pages are checked/served
6. `afterFiles` rewrites are checked/applied, if one of these rewrites is matched we check dynamic routes/static files after each match 6. `afterFiles` rewrites are checked/applied, if one of these rewrites is matched we check dynamic routes/static files after each match
......
...@@ -85,4 +85,4 @@ module.exports = { ...@@ -85,4 +85,4 @@ module.exports = {
#### `nextRuntime` #### `nextRuntime`
Notice that `isServer` is `true` when `nextRuntime` is `"edge"` or `"nodejs"`, `nextRuntime` `"edge"` is currently for middleware and Server Components in edge runtime only. Notice that `isServer` is `true` when `nextRuntime` is `"edge"` or `"nodejs"`, `nextRuntime` `"edge"` is currently for proxy and Server Components in edge runtime only.
...@@ -226,13 +226,13 @@ export default function Example() { ...@@ -226,13 +226,13 @@ export default function Example() {
} }
``` ```
The same applies for redirecting routes defined by middleware: The same applies for redirecting routes defined by proxy:
```ts filename="middleware.ts" ```ts filename="proxy.ts"
import { NextRequest, NextResponse } from 'next/server' import { NextRequest, NextResponse } from 'next/server'
export function middleware(request: NextRequest) { export function proxy(request: NextRequest) {
if (request.nextUrl.pathname === '/middleware-redirect') { if (request.nextUrl.pathname === '/proxy-redirect') {
return NextResponse.redirect(new URL('/', request.url)) return NextResponse.redirect(new URL('/', request.url))
} }
...@@ -244,7 +244,7 @@ export function middleware(request: NextRequest) { ...@@ -244,7 +244,7 @@ export function middleware(request: NextRequest) {
import type { Route } from 'next' import type { Route } from 'next'
export default function Page() { export default function Page() {
return <Link href={'/middleware-redirect' as Route}>Link Text</Link> return <Link href={'/proxy-redirect' as Route}>Link Text</Link>
} }
``` ```
......
...@@ -8,7 +8,7 @@ description: API Reference for the Edge Runtime. ...@@ -8,7 +8,7 @@ description: API Reference for the Edge Runtime.
Next.js has two server runtimes you can use in your application: Next.js has two server runtimes you can use in your application:
- The **Node.js Runtime** (default), which has access to all Node.js APIs and is used for rendering your application. - The **Node.js Runtime** (default), which has access to all Node.js APIs and is used for rendering your application.
- The **Edge Runtime** which contains a more limited [set of APIs](#reference), used in [Middleware](/docs/app/api-reference/file-conventions/middleware). - The **Edge Runtime** which contains a more limited [set of APIs](#reference), used in [Proxy](/docs/app/api-reference/file-conventions/proxy).
## Caveats ## Caveats
...@@ -159,9 +159,9 @@ The following JavaScript language features are disabled, and **will not work:** ...@@ -159,9 +159,9 @@ The following JavaScript language features are disabled, and **will not work:**
| [`WebAssembly.instantiate`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate) | Compiles and instantiates a WebAssembly module from a buffer source | | [`WebAssembly.instantiate`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate) | Compiles and instantiates a WebAssembly module from a buffer source |
In rare cases, your code could contain (or import) some dynamic code evaluation statements which _can not be reached at runtime_ and which can not be removed by treeshaking. In rare cases, your code could contain (or import) some dynamic code evaluation statements which _can not be reached at runtime_ and which can not be removed by treeshaking.
You can relax the check to allow specific files with your Middleware configuration: You can relax the check to allow specific files with your Proxy configuration:
```javascript filename="middleware.ts" ```javascript filename="proxy.ts"
export const config = { export const config = {
unstable_allowDynamic: [ unstable_allowDynamic: [
// allows a single file // allows a single file
......
...@@ -144,7 +144,7 @@ When using Sub-path Routing, the user would be redirected to `/fr`. ...@@ -144,7 +144,7 @@ When using Sub-path Routing, the user would be redirected to `/fr`.
### Prefixing the Default Locale ### Prefixing the Default Locale
With Next.js 12 and [Middleware](/docs/pages/api-reference/file-conventions/middleware), we can add a prefix to the default locale with a [workaround](https://github.com/vercel/next.js/discussions/18419). With Next.js 12 and [Proxy](/docs/pages/api-reference/file-conventions/proxy), we can add a prefix to the default locale with a [workaround](https://github.com/vercel/next.js/discussions/18419).
For example, here's a `next.config.js` file with support for a few languages. Note the `"default"` locale has been added intentionally. For example, here's a `next.config.js` file with support for a few languages. Note the `"default"` locale has been added intentionally.
...@@ -159,14 +159,14 @@ module.exports = { ...@@ -159,14 +159,14 @@ module.exports = {
} }
``` ```
Next, we can use [Middleware](/docs/pages/api-reference/file-conventions/middleware) to add custom routing rules: Next, we can use [Proxy](/docs/pages/api-reference/file-conventions/proxy) to add custom routing rules:
```ts filename="middleware.ts" ```ts filename="proxy.ts"
import { NextRequest, NextResponse } from 'next/server' import { NextRequest, NextResponse } from 'next/server'
const PUBLIC_FILE = /\.(.*)$/ const PUBLIC_FILE = /\.(.*)$/
export async function middleware(req: NextRequest) { export async function proxy(req: NextRequest) {
if ( if (
req.nextUrl.pathname.startsWith('/_next') || req.nextUrl.pathname.startsWith('/_next') ||
req.nextUrl.pathname.includes('/api/') || req.nextUrl.pathname.includes('/api/') ||
...@@ -185,7 +185,7 @@ export async function middleware(req: NextRequest) { ...@@ -185,7 +185,7 @@ export async function middleware(req: NextRequest) {
} }
``` ```
This [Middleware](/docs/pages/api-reference/file-conventions/middleware) skips adding the default prefix to [API Routes](/docs/pages/building-your-application/routing/api-routes) and [public](/docs/pages/api-reference/file-conventions/public-folder) files like fonts or images. If a request is made to the default locale, we redirect to our prefix `/en`. This [Proxy](/docs/pages/api-reference/file-conventions/proxy) skips adding the default prefix to [API Routes](/docs/pages/building-your-application/routing/api-routes) and [public](/docs/pages/api-reference/file-conventions/public-folder) files like fonts or images. If a request is made to the default locale, we redirect to our prefix `/en`.
### Disabling Automatic Locale Detection ### Disabling Automatic Locale Detection
...@@ -352,4 +352,4 @@ export async function getStaticProps({ locale }) { ...@@ -352,4 +352,4 @@ export async function getStaticProps({ locale }) {
- `locales`: 100 total locales - `locales`: 100 total locales
- `domains`: 100 total locale domain items - `domains`: 100 total locale domain items
> **Good to know**: These limits have been added initially to prevent potential [performance issues at build time](#dynamic-routes-and-getstaticprops-pages). You can workaround these limits with custom routing using [Middleware](/docs/pages/api-reference/file-conventions/middleware) in Next.js 12. > **Good to know**: These limits have been added initially to prevent potential [performance issues at build time](#dynamic-routes-and-getstaticprops-pages). You can workaround these limits with custom routing using [Proxy](/docs/pages/api-reference/file-conventions/proxy) in Next.js 12.
...@@ -181,4 +181,4 @@ router.push('/?counter=10', '/about?counter=10', { shallow: true }) ...@@ -181,4 +181,4 @@ router.push('/?counter=10', '/about?counter=10', { shallow: true })
Since that's a new page, it'll unload the current page, load the new one and wait for data fetching even though we asked to do shallow routing. Since that's a new page, it'll unload the current page, load the new one and wait for data fetching even though we asked to do shallow routing.
When shallow routing is used with middleware it will not ensure the new page matches the current page like previously done without middleware. This is due to middleware being able to rewrite dynamically and can't be verified client-side without a data fetch which is skipped with shallow, so a shallow route change must always be treated as shallow. When shallow routing is used with proxy it will not ensure the new page matches the current page like previously done without proxy. This is due to proxy being able to rewrite dynamically and can't be verified client-side without a data fetch which is skipped with shallow, so a shallow route change must always be treated as shallow.
...@@ -6,7 +6,7 @@ description: Next.js supports API Routes, which allow you to build your API with ...@@ -6,7 +6,7 @@ description: Next.js supports API Routes, which allow you to build your API with
<details> <details>
<summary>Examples</summary> <summary>Examples</summary>
- [API Routes Request Helpers](https://github.com/vercel/next.js/tree/canary/examples/api-routes-middleware) - [API Routes Request Helpers](https://github.com/vercel/next.js/tree/canary/examples/api-routes-proxy)
- [API Routes with GraphQL](https://github.com/vercel/next.js/tree/canary/examples/api-routes-graphql) - [API Routes with GraphQL](https://github.com/vercel/next.js/tree/canary/examples/api-routes-graphql)
- [API Routes with REST](https://github.com/vercel/next.js/tree/canary/examples/api-routes-rest) - [API Routes with REST](https://github.com/vercel/next.js/tree/canary/examples/api-routes-rest)
- [API Routes with CORS](https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors) - [API Routes with CORS](https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors)
......
...@@ -51,7 +51,7 @@ You should use `getStaticProps` if: ...@@ -51,7 +51,7 @@ You should use `getStaticProps` if:
- The data required to render the page is available at build time ahead of a user’s request - The data required to render the page is available at build time ahead of a user’s request
- The data comes from a headless CMS - The data comes from a headless CMS
- The page must be pre-rendered (for SEO) and be very fast — `getStaticProps` generates `HTML` and `JSON` files, both of which can be cached by a CDN for performance - The page must be pre-rendered (for SEO) and be very fast — `getStaticProps` generates `HTML` and `JSON` files, both of which can be cached by a CDN for performance
- The data can be publicly cached (not user-specific). This condition can be bypassed in certain specific situation by using a Middleware to rewrite the path. - The data can be publicly cached (not user-specific). This condition can be bypassed in certain specific situation by using a Proxy to rewrite the path.
## When does getStaticProps run ## When does getStaticProps run
...@@ -65,7 +65,7 @@ You should use `getStaticProps` if: ...@@ -65,7 +65,7 @@ You should use `getStaticProps` if:
When combined with [Incremental Static Regeneration](/docs/pages/guides/incremental-static-regeneration), `getStaticProps` will run in the background while the stale page is being revalidated, and the fresh page served to the browser. When combined with [Incremental Static Regeneration](/docs/pages/guides/incremental-static-regeneration), `getStaticProps` will run in the background while the stale page is being revalidated, and the fresh page served to the browser.
`getStaticProps` does not have access to the incoming request (such as query parameters or HTTP headers) as it generates static HTML. If you need access to the request for your page, consider using [Middleware](/docs/pages/api-reference/file-conventions/middleware) in addition to `getStaticProps`. `getStaticProps` does not have access to the incoming request (such as query parameters or HTTP headers) as it generates static HTML. If you need access to the request for your page, consider using [Proxy](/docs/pages/api-reference/file-conventions/proxy) in addition to `getStaticProps`.
## Using getStaticProps to fetch data from a CMS ## Using getStaticProps to fetch data from a CMS
......
---
title: Middleware
description: Learn how to use Middleware to run code before a request is completed.
source: app/api-reference/file-conventions/middleware
---
{/* 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. */}
--- ---
title: experimental.middlewareClientMaxBodySize title: experimental.proxyClientMaxBodySize
description: Configure the maximum request body size when using middleware. description: Configure the maximum request body size when using proxy.
source: app/api-reference/config/next-config-js/middlewareClientMaxBodySize source: app/api-reference/config/next-config-js/proxyClientMaxBodySize
--- ---
{/* 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. */} {/* 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. */}
---
title: Addressing "Beta Middleware Used" Error in Next.js
description: This document clarifies the "Beta Middleware Used" error in Next.js and provides a potential solution to fix it.
---
## Why This Error Occurred
The "Beta Middleware Used" error occurs if you are using [Middleware](/docs/pages/api-reference/file-conventions/middleware) in a version of Next.js prior to `v12.2`. The Middleware feature was still in beta in those versions and not yet covered by [semver](https://semver.org/) or Semantic Versioning rules.
## Possible Ways to Fix It
Despite this error, you can continue using Middleware in versions prior to `v12.2`. Be aware that **upgrading to newer versions of Next.js will require changes to your application to accommodate updates in Middleware handling**.
If you're using Next.js on Vercel, your existing deployments using Middleware will remain functional, and you can keep deploying your site with Middleware. However, when you decide to upgrade your site to Next.js `v12.2` or later, you'll need to follow the provided [upgrade guide](/docs/messages/middleware-upgrade-guide) to ensure compatibility.
## Useful Links
- [Middleware Upgrade Guide](/docs/messages/middleware-upgrade-guide) - Learn more about the necessary steps to upgrade your application to a version of Next.js that includes the official version of Middleware.
---
title: Deleting Query Parameters In Middlewares
---
## Why This Error Occurred
In previous versions of Next.js, we were merging query parameters with the incoming request for rewrites happening in middlewares, 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="middleware.ts"
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
export default function middleware(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="middleware.ts"
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
export default function middleware(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.
--- ---
title: Dynamic code evaluation is not available in Middleware title: Dynamic code evaluation is not available in Proxy
--- ---
## Why This Error Occurred ## Why This Error Occurred
`eval()`, `new Function()` or compiling WASM binaries dynamically is not allowed in Middleware. `eval()`, `new Function()` or compiling WASM binaries dynamically is not allowed in Proxy.
Specifically, the following APIs are not supported: Specifically, the following APIs are not supported:
- `eval()` - `eval()`
...@@ -16,11 +16,11 @@ Specifically, the following APIs are not supported: ...@@ -16,11 +16,11 @@ Specifically, the following APIs are not supported:
You can bundle your WASM binaries using `import`: You can bundle your WASM binaries using `import`:
```ts filename="middleware.ts" ```ts filename="proxy.ts"
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
import squareWasm from './square.wasm?module' import squareWasm from './square.wasm?module'
export default async function middleware() { export default async function proxy() {
const m = await WebAssembly.instantiate(squareWasm) const m = await WebAssembly.instantiate(squareWasm)
const answer = m.exports.square(9) const answer = m.exports.square(9)
...@@ -31,7 +31,7 @@ export default async function middleware() { ...@@ -31,7 +31,7 @@ export default async function middleware() {
``` ```
In rare cases, your code could contain (or import) some dynamic code evaluation statements which _can not be reached at runtime_ and which can not be removed by tree-shaking. In rare cases, your code could contain (or import) some dynamic code evaluation statements which _can not be reached at runtime_ and which can not be removed by tree-shaking.
You can relax the check to allow specific files with your Middleware [configuration](/docs/pages/api-reference/edge#unsupported-apis): You can relax the check to allow specific files with your Proxy [configuration](/docs/pages/api-reference/edge#unsupported-apis):
```ts filename="pages/api/example.ts" ```ts filename="pages/api/example.ts"
export const config = { export const config = {
......
...@@ -14,7 +14,7 @@ For this reason, accessing the object after this time is disallowed. ...@@ -14,7 +14,7 @@ For this reason, accessing the object after this time is disallowed.
You can fix this error by moving any access of the `res` object into `getServerSideProps()` itself or any functions that run before `getServerSideProps()` returns. You can fix this error by moving any access of the `res` object into `getServerSideProps()` itself or any functions that run before `getServerSideProps()` returns.
If you’re using a custom server and running into this problem due to session middleware like `next-session` or `express-session`, try installing the middleware in the server instead of `getServerSideProps()`. If you’re using a custom server and running into this problem due to session proxy like `next-session` or `express-session`, try installing the proxy in the server instead of `getServerSideProps()`.
## Useful Links ## Useful Links
......
...@@ -4,7 +4,7 @@ title: 'Invalid Custom Route `source`' ...@@ -4,7 +4,7 @@ title: 'Invalid Custom Route `source`'
## Why This Error Occurred ## Why This Error Occurred
A pattern could not be parsed when defining custom routes or a middleware `matcher`. A pattern could not be parsed when defining custom routes or a proxy `matcher`.
This could have been due to trying to use normal `RegExp` syntax like negative lookaheads (`?!exclude`) without following [`path-to-regexp`](https://github.com/pillarjs/path-to-regexp)'s syntax. This could have been due to trying to use normal `RegExp` syntax like negative lookaheads (`?!exclude`) without following [`path-to-regexp`](https://github.com/pillarjs/path-to-regexp)'s syntax.
...@@ -32,11 +32,11 @@ Wrap the `RegExp` part of your `source` as an un-named parameter. ...@@ -32,11 +32,11 @@ Wrap the `RegExp` part of your `source` as an un-named parameter.
} }
``` ```
### Middleware ### Proxy
**Before** **Before**
```ts filename="middleware.ts" ```ts filename="proxy.ts"
const config = { const config = {
matcher: '/feedback/(?!general)', matcher: '/feedback/(?!general)',
} }
...@@ -44,7 +44,7 @@ const config = { ...@@ -44,7 +44,7 @@ const config = {
**After** **After**
```ts filename="middleware.ts" ```ts filename="proxy.ts"
const config = { const config = {
matcher: '/feedback/((?!general).*)', matcher: '/feedback/((?!general).*)',
} }
......
---
title: Dynamic WASM compilation is not available in Middlewares
---
## Why This Error Occurred
Compiling WASM binaries dynamically is not allowed in Middlewares. 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="middleware.ts"
import { NextResponse } from 'next/server'
import squareWasm from './square.wasm?module'
export default async function middleware() {
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 Middleware API Signature
---
## Why This Error Occurred
Your application is using a Middleware function that is using parameters from the deprecated API.
```ts filename="middleware.ts"
import { NextResponse } from 'next/server'
export function middleware(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 Middleware:
```ts filename="middleware.ts"
import { NextResponse } from 'next/server'
export function middleware(request) {
if (request.nextUrl.pathname === '/blocked') {
return new NextResponse(null, {
status: 403,
})
}
}
```
---
title: Removed parsed User Agent from Middleware API
---
## Why This Error Occurred
Your application is interacting with `req.ua` which has been deprecated.
```ts filename="middleware.ts"
import { NextRequest, NextResponse } from 'next/server'
export function middleware(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="middleware.ts"
import { NextRequest, NextResponse, userAgent } from 'next/server'
export function middleware(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: 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)
---
title: Removed page from Middleware API
---
## Why This Error Occurred
Your application is interacting with `request.page` which has been deprecated.
```ts filename="middleware.ts"
import { NextRequest, NextResponse } from 'next/server'
export function middleware(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="middleware.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 middleware(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 Middleware API
---
## Why This Error Occurred
Your middleware is interacting with `req.ua` and this feature needs to opt-in.
```ts filename="middleware.ts"
import { NextRequest, NextResponse } from 'next/server'
export function middleware(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="middleware.ts"
import { NextRequest, NextResponse, userAgent } from 'next/server'
export function middleware(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)
}
```
---
title: Nested Middleware
---
## Why This Error Occurred
You are defining a Middleware file in a location different from `<root>/middleware`, which is not allowed.
While in beta, a Middleware file under specific pages would _only_ be executed when pages below its declaration were matched, allowing nesting Middleware files. Based on customer feedback, we have replaced this API with a single root Middleware.
## Possible Ways to Fix It
Declare your Middleware in the root folder and use `NextRequest` parsed URL to define which path the Middleware should be executed for.
For example, a Middleware at `pages/about/_middleware.ts` can move the logic to `<root>/middleware.ts` in the root of your repository. Then, a conditional statement can be used to only run the Middleware when it matches the `about/*` path:
```ts filename="middleware.ts"
import type { NextRequest } from 'next/server'
export function middleware(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 Middleware, you should combine them into a single file and model their execution depending on the incoming request.
...@@ -4,9 +4,9 @@ title: '`NextResponse.next()` used in a Route Handler in the App Router' ...@@ -4,9 +4,9 @@ title: '`NextResponse.next()` used in a Route Handler in the App Router'
## Why This Error Occurred ## Why This Error Occurred
Route Handlers in the Next.js App Router do not support using the `NextResponse.next()` method to forward to the next Middleware. Route Handlers in the Next.js App Router do not support using the `NextResponse.next()` method to forward to the next Proxy.
The Route Handler is considered the end of the middleware "chain". Handlers must always return a `Response` object instead. The Route Handler is considered the end of the proxy "chain". Handlers must always return a `Response` object instead.
## Possible Ways to Fix It ## Possible Ways to Fix It
......
...@@ -2,24 +2,24 @@ ...@@ -2,24 +2,24 @@
title: No Server Import In Page title: No Server Import In Page
--- ---
> Prevent usage of `next/server` outside of `middleware.js`. > Prevent usage of `next/server` outside of `proxy.js`.
## Why This Error Occurred ## Why This Error Occurred
`next/server` was imported outside of `middleware.{js,ts}`. `next/server` was imported outside of `proxy.{js,ts}`.
## Possible Ways to Fix It ## Possible Ways to Fix It
Only import and use `next/server` in a file located within the project root directory: `middleware.{js,ts}`. Only import and use `next/server` in a file located within the project root directory: `proxy.{js,ts}`.
```ts filename="middleware.ts" ```ts filename="proxy.ts"
import type { NextFetchEvent, NextRequest } from 'next/server' import type { NextFetchEvent, NextRequest } from 'next/server'
export function middleware(req: NextRequest, ev: NextFetchEvent) { export function proxy(req: NextRequest, ev: NextFetchEvent) {
return new Response('Hello, world!') return new Response('Hello, world!')
} }
``` ```
## Useful Links ## Useful Links
- [Middleware](/docs/pages/api-reference/file-conventions/middleware) - [Proxy](/docs/pages/api-reference/file-conventions/proxy)
...@@ -4,7 +4,7 @@ title: Using Node.js Modules in Edge Runtime ...@@ -4,7 +4,7 @@ title: Using Node.js Modules in Edge Runtime
## Why This Error Occurred ## Why This Error Occurred
The code in your [Middleware](/docs/pages/api-reference/file-conventions/middleware) or your [Edge API Routes](/docs/pages/building-your-application/routing/api-routes) is using a feature from Node.js runtime. The code in your [Proxy](/docs/pages/api-reference/file-conventions/proxy) or your [Edge API Routes](/docs/pages/building-your-application/routing/api-routes) is using a feature from Node.js runtime.
However, the Edge Runtime does not support [Node.js APIs and globals](/docs/pages/api-reference/edge#unsupported-apis). However, the Edge Runtime does not support [Node.js APIs and globals](/docs/pages/api-reference/edge#unsupported-apis).
...@@ -17,5 +17,5 @@ For example, you might replace the Node.js `crypto` module with the [Web Crypto ...@@ -17,5 +17,5 @@ For example, you might replace the Node.js `crypto` module with the [Web Crypto
## Useful Links ## Useful Links
- [Edge Runtime Supported APIs](/docs/pages/api-reference/edge) - [Edge Runtime Supported APIs](/docs/pages/api-reference/edge)
- [Next.js Middleware](/docs/pages/api-reference/file-conventions/middleware) - [Next.js Proxy](/docs/pages/api-reference/file-conventions/proxy)
- [JWT Example](https://vercel.com/templates/next.js/jwt-authentication) - [JWT Example](https://vercel.com/templates/next.js/jwt-authentication)
---
title: Returning response body in Middleware
---
> **Note**: In Next.js v13.0.0 you can now respond to Middleware directly by returning a `NextResponse`. For more information, see [Producing a Response](/docs/pages/api-reference/file-conventions/middleware#producing-a-response).
## Why This Error Occurred
[Middleware](/docs/pages/api-reference/file-conventions/middleware) can no longer produce a response body as of `v12.2+`.
## Possible Ways to Fix It
Migrate to using `rewrite`/`redirect` to Pages/API Routes handling a response.
### Explanation
To respect the differences in client-side and server-side navigation, and to help ensure that developers do not build insecure Middleware, Middleware can no longer produce a response body. This ensures that Middleware is only used to `rewrite`, `redirect`, or modify the incoming request (e.g. [setting cookies](/docs/pages/api-reference/file-conventions/middleware#using-cookies)).
The following patterns will no longer work:
```js
new Response('a text value')
new Response(streamOrBuffer)
new Response(JSON.stringify(obj), { headers: 'application/json' })
NextResponse.json()
```
### How to upgrade
For cases where Middleware is used to respond (such as authorization), you should migrate to use `rewrite`/`redirect` to pages that show an authorization error, login forms, or to an API Route.
#### Before
```ts filename="pages/_middleware.ts"
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { isAuthValid } from './lib/auth'
export function middleware(request: NextRequest) {
// Example function to validate auth
if (isAuthValid(request)) {
return NextResponse.next()
}
return NextResponse.json({ message: 'Auth required' }, { status: 401 })
}
```
#### After
```ts filename="middleware.ts"
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { isAuthValid } from './lib/auth'
export function middleware(request: NextRequest) {
// Example function to validate auth
if (isAuthValid(request)) {
return NextResponse.next()
}
request.nextUrl.searchParams.set('from', request.nextUrl.pathname)
request.nextUrl.pathname = '/login'
return NextResponse.redirect(request.nextUrl)
}
```
...@@ -54,7 +54,7 @@ export type MiddlewareMatcher = { ...@@ -54,7 +54,7 @@ export type MiddlewareMatcher = {
export type ProxyConfig = { export type ProxyConfig = {
/** /**
* The matcher for the middleware. Read more: [Next.js Docs: Middleware `matcher`](https://nextjs.org/docs/app/api-reference/file-conventions/middleware#matcher), * The matcher for the middleware. Read more: [Next.js Docs: Middleware `matcher`](https://nextjs.org/docs/app/api-reference/file-conventions/proxy#matcher),
* [Next.js Docs: Middleware matching paths](https://nextjs.org/docs/app/building-your-application/routing/middleware#matching-paths) * [Next.js Docs: Middleware matching paths](https://nextjs.org/docs/app/building-your-application/routing/middleware#matching-paths)
*/ */
matchers?: MiddlewareMatcher[] matchers?: MiddlewareMatcher[]
......
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