Skip to content

Next.js Proxy(原 Middleware)

Next.js 16 将 Middleware 更名为 Proxy,功能不变。

作用

功能示例
跨域处理设置 CORS 头
接口转发/api/* → 后端服务
鉴权检查 token,未登录重定向
限流IP 频率限制

配置

ts
// proxy.ts(项目根目录或 src 下)
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function proxy(request: NextRequest) {
  // 鉴权示例
  const token = request.cookies.get('token')
  if (!token) return NextResponse.redirect(new URL('/login', request.url))
  return NextResponse.next()
}

export const config = {
  matcher: ['/dashboard/:path*', '/api/:path*']
}

从旧版升级

bash
npx @next/codemod@canary middleware-to-proxy .