NextJs - Middleware(中间件)

中间件允许您在请求完成之前运行代码。然后,根据传入的请求,您可以通过重写、重定向、修改请求或响应标头或直接响应来修改响应。

中间件在缓存内容和路由匹配之前运行。

使用规则

使用项目根目录中的文件 middleware.ts(或 .js)来定义中间件。例如,与页面或应用程序处于同一级别,或者在 src 内部(如果适用)。

javascript 复制代码
// middleware.ts
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*',
}

匹配路径

将为项目中的每个路由调用中间件。以下是执行顺序:

  1. headers from next.config.js
  2. 来自 next.config.js的重定向
  3. 中间件(重写、重定向等)
  4. 来自 next.config.js 的 beforeFiles(重写)
  5. 文件系统路由(public/、_next/static/、pages/、app/等)
  6. 来自 next.config.js 的 afterFiles(重写)
  7. 动态路由 (/blog/slug)
  8. 从 next.config.js 回退(重写)

Matcher (匹配器)

matcher 允许您过滤中间件以在特定路径上运行。

javascript 复制代码
export const config = {
  matcher: '/about/:path*',
}

可以使用数组语法匹配单个路径或多个路径:

javascript 复制代码
export const config = {
  matcher: ['/about/:path*', '/dashboard/:path*'],
}

匹配器配置允许完整的正则表达式,因此支持负向查找或字符匹配等匹配。可以在此处查看用于匹配除特定路径之外的所有路径的负前瞻示例:

javascript 复制代码
export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
  ],
}

注意:

  • 匹配器值需要是常量,以便可以在构建时对其进行静态分析。诸如变量之类的动态值将被忽略。

Configured:

  1. 必须以 / 开头
  2. 可以包含命名参数: /about/:path 匹配 /about/a 和 /about/b 但不匹配 /about/a/c
  3. 可以对命名参数进行修饰符(以 :) 开头: /about/:path* 匹配 /about/a/b/c 因为 * 为零或更多。 ?为零或一且+一或多个
  4. 可以使用括号括起来的正则表达式:/about/(.*) 与/about/:path* 相同
相关推荐
2401_8685347811 小时前
中间件概念
中间件
小刘在重生~11 小时前
Django 全套入门笔记|安装、项目创建、ORM、Form、中间件、登录认证
笔记·中间件·django
花间相见2 天前
【LangChain中间件01】—— LangChain 中间件入门:六个钩子让 Agent 可插拔
中间件·langchain
姚不倒2 天前
HAProxy 系列(四):多中间件统一 VIP 入口 — 架构模式与最佳实践
运维·中间件·架构·haproxy
yoguo-2103 天前
TongWeb7控制台部署应用时,应用包大小限制
中间件·tongweb
__zRainy__4 天前
Node系列 · Express:cors 中间件
中间件·express
StevenSurpass4 天前
智能工厂场景:FastPrintAgent 分布式打印中间件落地应用方案
分布式·mqtt·http·中间件·打印·fastreport
程序员小八7775 天前
Go Web 工程化:日志、配置与错误处理中间件,让服务「能上线」
前端·中间件·golang
tqs_123455 天前
SaaS 多租户 Agent 平台实战:自研 Agent 中间件 SDK,Nacos 配置驱动实现开箱即用
中间件
未若君雅裁5 天前
自定义中间件:Node-style 与 Wrap-style 钩子全解析
python·中间件·langchain