路由处理程序和中间件
¥Route Handlers and Middleware
路由处理程序
¥Route Handlers
路由处理程序允许你使用 Web 请求 和 响应 API 为给定路由创建自定义请求处理程序。
¥Route Handlers allow you to create custom request handlers for a given route using the Web Request and Response APIs.

需要了解:路由处理程序仅在
app
目录中可用。它们相当于pages
目录中的 API 路由,这意味着你不需要同时使用 API 路由和路由处理程序。¥Good to know: Route Handlers are only available inside the
app
directory. They are the equivalent of API Routes inside thepages
directory meaning you do not need to use API Routes and Route Handlers together.
惯例
¥Convention
路由处理程序在 app
目录内的 route.js|ts
file 中定义:
¥Route Handlers are defined in a route.js|ts
file inside the app
directory:
export async function GET(request: Request) {}
路由处理程序可以嵌套在 app
目录内的任何位置,类似于 page.js
和 layout.js
。但不能有 route.js
文件与 page.js
处于同一航段级别。
¥Route Handlers can be nested anywhere inside the app
directory, similar to page.js
and layout.js
. But there cannot be a route.js
file at the same route segment level as page.js
.
支持的 HTTP 方法
¥Supported HTTP Methods
支持以下 HTTP 方法:GET
、POST
、PUT
、PATCH
、DELETE
、HEAD
和 OPTIONS
。如果调用不受支持的方法,Next.js 将返回 405 Method Not Allowed
响应。
¥The following HTTP methods are supported: GET
, POST
, PUT
, PATCH
, DELETE
, HEAD
, and OPTIONS
. If an unsupported method is called, Next.js will return a 405 Method Not Allowed
response.
扩展 NextRequest
和 NextResponse
API
¥Extended NextRequest
and NextResponse
APIs
除了支持原生 请求 和 响应 API 之外,Next.js 还使用 NextRequest
和 NextResponse
扩展了它们,为高级用例提供方便的辅助程序。
¥In addition to supporting the native Request and Response APIs, Next.js extends them with NextRequest
and NextResponse
to provide convenient helpers for advanced use cases.
缓存
¥Caching
默认情况下,路由处理程序不缓存。但是,你可以选择缓存 GET
方法。其他支持的 HTTP 方法不会被缓存。要缓存 GET
方法,请在路由处理程序文件中使用 路由配置选项(例如 export const dynamic = 'force-static'
)。
¥Route Handlers are not cached by default. You can, however, opt into caching for GET
methods. Other supported HTTP methods are not cached. To cache a GET
method, use a route config option such as export const dynamic = 'force-static'
in your Route Handler file.
export const dynamic = 'force-static'
export async function GET() {
const res = await fetch('https://data.mongodb-api.com/...', {
headers: {
'Content-Type': 'application/json',
'API-Key': process.env.DATA_API_KEY,
},
})
const data = await res.json()
return Response.json({ data })
}
需要了解:其他支持的 HTTP 方法不会被缓存,即使它们与缓存的
GET
方法放在同一个文件中。¥Good to know: Other supported HTTP methods are not cached, even if they are placed alongside a
GET
method that is cached, in the same file.
特殊路由处理程序
¥Special Route Handlers
特殊路由处理程序(如 sitemap.ts
、opengraph-image.tsx
和 icon.tsx
)和其他 元数据文件 默认保持静态,除非它们使用动态 API 或动态配置选项。
¥Special Route Handlers like sitemap.ts
, opengraph-image.tsx
, and icon.tsx
, and other metadata files remain static by default unless they use Dynamic APIs or dynamic config options.
路由解析
¥Route Resolution
你可以将 route
视为最底层的路由原语。
¥You can consider a route
the lowest level routing primitive.
它们不像
page
那样参与布局或客户端导航。¥They do not participate in layouts or client-side navigations like
page
.route.js
文件不能与page.js
在同一路径上。¥There cannot be a
route.js
file at the same route aspage.js
.
页面 | 路由 | 结果 |
---|---|---|
app/page.js | app/route.js | 冲突 |
app/page.js | app/api/route.js | 有效 |
app/[user]/page.js | app/api/route.js | 有效 |
每个 route.js
或 page.js
文件都会接管该路由的所有 HTTP 动词。
¥Each route.js
or page.js
file takes over all HTTP verbs for that route.
export default function Page() {
return <h1>Hello, Next.js!</h1>
}
// ❌ Conflict
// `app/route.ts`
export async function POST(request: Request) {}
了解更多关于路由处理程序 补充你的前端应用 的信息,或探索路由处理程序 API 参考。
¥Read more about how Route Handlers complement your frontend application, or explore the Route Handlers API Reference.
中间件
¥Middleware
中间件允许你在请求完成之前运行代码。然后,根据传入的请求,你可以通过重写、重定向、修改请求或响应标头或直接响应来修改响应。
¥Middleware allows you to run code 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.
用例
¥Use cases
中间件有效的一些常见场景包括:
¥Some common scenarios where Middleware is effective include:
读取部分传入请求后快速重定向
¥Quick redirects after reading parts of the incoming request
根据 A/B 测试或实验重写到不同的页面
¥Rewriting to different pages based on A/B tests or experiments
修改所有页面或部分页面的标题
¥Modifying headers for all pages or a subset of pages
中间件不适用于:
¥Middleware is not a good fit for:
数据获取速度慢
¥Slow data fetching
会话管理
¥Session management
在中间件中,使用 options.cache
、options.next.revalidate
或 options.next.tags
进行 fetch 操作无效。
¥Using fetch with options.cache
, options.next.revalidate
, or options.next.tags
, has no effect in Middleware.
惯例
¥Convention
使用项目根目录中的文件 middleware.ts
(或 .js
)来定义中间件。例如,与 pages
或 app
处于同一级别,或者在 src
内部(如果适用)。
¥Use the file middleware.ts
(or .js
) in the root of your project to define Middleware. For example, at the same level as pages
or app
, or inside src
if applicable.
注意:虽然每个项目仅支持一个
middleware.ts
文件,但你仍然可以将中间件逻辑组织到模块中。将中间件函数分解为单独的.ts
或.js
文件,并将它们导入到主middleware.ts
文件中。这样可以对特定于路由的中间件进行更清晰的管理,这些中间件聚合在middleware.ts
中以进行集中控制。通过强制执行单个中间件文件,它可以简化配置,防止潜在冲突,并通过避免多个中间件层来优化性能。¥Note: While only one
middleware.ts
file is supported per project, you can still organize your middleware logic into modules. Break out middleware functionalities into separate.ts
or.js
files and import them into your mainmiddleware.ts
file. This allows for cleaner management of route-specific middleware, aggregated in themiddleware.ts
for centralized control. By enforcing a single middleware file, it simplifies configuration, prevents potential conflicts, and optimizes performance by avoiding multiple middleware layers.
示例
¥Example
import { NextResponse } from 'next/server'
import type { 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))
}
// See "Matching Paths" below to learn more
export const config = {
matcher: '/about/:path*',
}
了解更多关于 使用 middleware
的信息,或参考 middleware
API 参考。
¥Read more about using middleware
, or refer to the middleware
API reference.