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* 相同
相关推荐
利白6 小时前
iceoryx高性能进程间通信中间件,在Windows环境的编译教程
中间件·内存·进程通信·ipc·iceoryx
小红帽2.020 小时前
GOFLY开源客服系统-处理gin框架下的session中间件
中间件·gin
Ray Song1 天前
MCAP :机器人数据容器的全面实践指南
中间件·自动驾驶·dds·mcap
Ray Song1 天前
【FastDDS】Layer Transport ( 05-Shared Memory Transport)
中间件·自动驾驶·dds·fastdds
北执南念1 天前
数据库中间件ShardingSphere v5.2.1
数据库·中间件
红鼻子时代1 天前
Day5-中间件与请求处理
中间件·fastapi·后端开发
只因在人海中多看了你一眼1 天前
B.50.10.01-消息队列与电商应用
中间件
子非鱼@Itfuture2 天前
【Kafka】Kafka使用场景用例&Kafka用例图
分布式·中间件·kafka
中国胖子风清扬2 天前
Rust 序列化技术全解析:从基础到实战
开发语言·c++·spring boot·vscode·后端·中间件·rust
Lilixxs2 天前
VBA 中使用 ADODB 操作 SQLite 插入中文乱码问题
数据库·中间件·sqlite·乱码·vba·odbc·adodb