middleware.js
middleware.js|ts
文件用于在请求完成之前写入 中间件 并在服务器上运行代码。然后,根据传入的请求,你可以通过重写、重定向、修改请求或响应标头或直接响应来修改响应。
¥The middleware.js|ts
file is used to write Middleware and run code on the server before a request is completed. Then, based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly.
中间件在渲染路由之前执行。它对于实现自定义服务器端逻辑(例如身份验证、日志记录或处理重定向)特别有用。
¥Middleware executes before routes are rendered. It's particularly useful for implementing custom server-side logic like authentication, logging, or handling redirects.
使用项目根目录中的文件 middleware.ts
(或 .js)来定义中间件。例如,与 app
或 pages
处于同一级别,或者在 src
内部(如果适用)。
¥Use the file middleware.ts
(or .js) in the root of your project to define Middleware. For example, at the same level as app
or pages
, or inside src
if applicable.
import { NextResponse, NextRequest } from 'next/server'
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
return NextResponse.redirect(new URL('/home', request.url))
}
export const config = {
matcher: '/about/:path*',
}
import { NextResponse } from 'next/server'
// This function can be marked `async` if using `await` inside
export function middleware(request) {
return NextResponse.redirect(new URL('/home', request.url))
}
export const config = {
matcher: '/about/:path*',
}
导出
¥Exports
中间件函数
¥Middleware function
该文件必须导出单个函数,作为默认导出或命名为 middleware
。请注意,不支持来自同一文件的多个中间件。
¥The file must export a single function, either as a default export or named middleware
. Note that multiple middleware from the same file are not supported.
// Example of default export
export default function middleware(request) {
// Middleware logic
}
配置对象(可选)
¥Config object (optional)
(可选)配置对象可以与中间件函数一起导出。该对象包括 matcher 以指定中间件应用的路径。
¥Optionally, a config object can be exported alongside the Middleware function. This object includes the matcher to specify paths where the Middleware applies.
匹配器
¥Matcher
matcher
选项允许你指定中间件运行的特定路径。你可以通过多种方式指定这些路径:
¥The matcher
option allows you to target specific paths for the Middleware to run on. You can specify these paths in several ways:
-
对于单个路径:直接用字符串定义路径,如
'/about'
。¥For a single path: Directly use a string to define the path, like
'/about'
. -
对于多个路径:使用数组列出多个路径,例如
matcher: ['/about', '/contact']
,它将中间件应用到/about
和/contact
。¥For multiple paths: Use an array to list multiple paths, such as
matcher: ['/about', '/contact']
, which applies the Middleware to both/about
and/contact
.
此外,matcher
通过正则表达式支持复杂的路径规范,例如 matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)']
,从而可以精确控制要包含或排除的路径。
¥Additionally, matcher
supports complex path specifications through regular expressions, such as matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)']
, enabling precise control over which paths to include or exclude.
matcher
选项还接受具有以下键的对象数组:
¥The matcher
option also accepts an array of objects with the following keys:
-
source
:用于匹配请求路径的路径或模式。它可以是用于直接路径匹配的字符串,也可以是用于更复杂匹配的模式。¥
source
: The path or pattern used to match the request paths. It can be a string for direct path matching or a pattern for more complex matching. -
regexp
(可选):一个正则表达式字符串,根据源微调匹配。它提供了对包含或排除哪些路径的额外控制。¥
regexp
(optional): A regular expression string that fine-tunes the matching based on the source. It provides additional control over which paths are included or excluded. -
locale
(可选):一个布尔值,当设置为false
时,将忽略路径匹配中基于区域设置的路由。¥
locale
(optional): A boolean that, when set tofalse
, ignores locale-based routing in path matching. -
has
(可选):根据特定请求元素(例如标头、查询参数或 cookie)的存在来指定条件。¥
has
(optional): Specifies conditions based on the presence of specific request elements such as headers, query parameters, or cookies. -
missing
(可选):重点关注缺少某些请求元素的情况,例如缺少标头或 cookie。¥
missing
(optional): Focuses on conditions where certain request elements are absent, like missing headers or cookies.
export const config = {
matcher: [
{
source: '/api/*',
regexp: '^/api/(.*)',
locale: false,
has: [
{ type: 'header', key: 'Authorization', value: 'Bearer Token' },
{ type: 'query', key: 'userId', value: '123' },
],
missing: [{ type: 'cookie', key: 'session', value: 'active' }],
},
],
}
参数
¥Params
request
定义中间件时,默认导出函数接受单个参数 request
。该参数是 NextRequest
的实例,代表传入的 HTTP 请求。
¥When defining Middleware, the default export function accepts a single parameter, request
. This parameter is an instance of NextRequest
, which represents the incoming HTTP request.
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
// Middleware logic goes here
}
export function middleware(request) {
// Middleware logic goes here
}
很高兴知道:
¥Good to know:
NextRequest
是代表 Next.js 中间件中传入 HTTP 请求的类型,而NextResponse
是用于操作和发回 HTTP 响应的类。¥
NextRequest
is a type that represents incoming HTTP requests in Next.js Middleware, whereasNextResponse
is a class used to manipulate and send back HTTP responses.
NextResponse
中间件可以使用扩展了 网络响应 API 的 NextResponse
对象。通过返回 NextResponse
对象,你可以直接操作 cookie、设置标头、实现重定向和重写路径。
¥Middleware can use the NextResponse
object which extends the Web Response API. By returning a NextResponse
object, you can directly manipulate cookies, set headers, implement redirects, and rewrite paths.
很高兴知道:对于重定向,你还可以使用
Response.redirect
而不是NextResponse.redirect
。¥Good to know: For redirects, you can also use
Response.redirect
instead ofNextResponse.redirect
.
运行时
¥Runtime
中间件仅支持 边缘运行时。无法使用 Node.js 运行时。
¥Middleware only supports the Edge runtime. The Node.js runtime cannot be used.
版本历史
¥Version History
版本 | 变化 |
---|---|
v13.1.0 | 添加了高级中间件标志 |
v13.0.0 | 中间件可以修改请求头、响应头、发送响应 |
v12.2.0 | 中间件稳定,请参见 升级指南 |
v12.0.9 | 在 Edge Runtime 中强制使用绝对 URL (PR) |
v12.0.0 | 添加了中间件(测试版) |