Middleware 是在请求完成之前运行的代码 — 在 Edge 上,在页面或路由处理程序渲染之前。它让你能够检查和重写/重定向请求、设置标头,或在一个地方检查许多路由的身份验证。
定义 middleware
ts
{ , } ;
() {
token = req..()?.;
(req...() && !token) {
.( (, req.));
}
.();
}
config = { : [, ] };
NextResponse.redirect(url); // send the user elsewhere (auth gates)
NextResponse.rewrite(url); // serve different content, URL unchanged (A/B, i18n)
NextResponse.next(); // continue, optionally with modified headers
// req.geo / req.cookies / req.headers — inspect location, auth, etc.
常见用途:身份验证网关、重定向(基于地区/地理位置、www→apex)、通过重写进行 A/B 测试、设置安全标头,以及 bot/特性开关。
⚠️ Runs on the EDGE runtime → no Node.js APIs (no fs, limited libraries)
⚠️ Must be FAST — it runs before every matched request; heavy work adds latency
⚠️ Can't access the database directly for complex auth — do lightweight checks
(e.g. verify a JWT/cookie exists); do full auth in the page/handler
matcher 配置很重要:将 middleware 的范围限制在只有需要它的路由上,这样它就不会在静态资源上运行并拖慢整个应用。
Middleware 是横切关注点请求逻辑的唯一控制点 — 身份验证重定向、地区路由、重写和标头 — 应用于许多路由,无需在每个页面中重复代码。
了解其 Edge 约束(快速、无 Node API、仅轻量级检查)和 matcher 作用域是让你能够正确使用它来处理网关和路由关注点的关键。