Next.js Middleware中与Express的app.use()等效的实现方式是什么?
Next.js Middleware 对应 Express
app.use() 的实现方式 在 Next.js Middleware 里,全局或指定路由的中间件逻辑就对应 Express 中的 app.use(),具体分两种场景:
1. 全局生效的中间件
如果想让中间件作用于所有请求(就像 Express 里直接用 app.use((req, res, next) => { ... })),只需要在项目根目录创建 middleware.ts(或 .js)文件,编写核心逻辑即可。
示例代码:
import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' export function middleware(request: NextRequest) { // 所有请求都会走这里,比如打日志、做身份校验 console.log(`请求路径: ${request.nextUrl.pathname}`) // 放行请求,对应 Express 的 next() return NextResponse.next() }
2. 针对特定路由的中间件
如果要让中间件只作用于特定路由(类似 app.use('/api', yourMiddleware)),可以通过 config.matcher 配置匹配规则,或者在中间件里直接判断路径:
示例代码(用 matcher 配置):
import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' export function middleware(request: NextRequest) { // 这里的逻辑只对 matcher 匹配的路由生效 console.log(`API 请求路径: ${request.nextUrl.pathname}`) return NextResponse.next() } export const config = { // 匹配所有 API 路由和 dashboard 路由 matcher: ['/api/:path*', '/dashboard/:path*'], }
核心区别
- Express 是按挂载顺序执行中间件链,Next.js Middleware 则是基于路由匹配来触发,更偏向路由守卫的模式。
- Next.js 里用
NextResponse.next()放行请求,对应 Express 的next();如果要重定向或修改响应,直接返回NextResponse.redirect()或自定义响应即可。
内容的提问来源于stack exchange,提问作者YulePale
相关产品推荐
相关产品推荐

