前言
middleware.ts中两个方法 middleware中间件 和 config matcher(匹配器)
在next项目中经常看到middleware.ts文件;官网代码
import type { NextFetchEvent, NextRequest } from 'next/server'
export function middleware(req: NextRequest, ev: NextFetchEvent) {
return new Response('Hello, world!')
}
Middleware中间件允许在请求完成之前运行代码;根据传入的请求req,通过重写、重定向、修改请求或响应头来修改响应。
使用示例
import { NextRequest, NextResponse } from "next/server";
import parser from "ua-parser-js";
/**
* 一个异步中间件函数,用于处理请求并进行重定向或重写URL。
* @param req - Next.js 的请求对象,包含请求的详细信息。
* @returns 返回一个 Promise,解析为 NextResponse 对象,用于响应请求。
*/
export async function middleware(req: NextRequest) {
// 克隆URL对象,以便修改而不影响原始请求
const url = req.nextUrl.clone();
// 获取并处理用户代理字符串
const userAgent = req.headers.get("user-agent")?.toLocaleLowerCase();
const userAgentInst = parser(userAgent!);
// 根据用户代理判断设备类型,并据此修改URL路径
const viewport =
userAgentInst.device.type === "mobile" ? "mobile" : "pc";
url.pathname = `/${viewport}${url.pathname}`.replace(/\/$/, "");
// 如果路径包含 "/desktop",重定向到百度
if (url.pathname.includes(`/desktop`)) {
return NextResponse.redirect(`https://www.baidu.com`);
}
// 对路径进行重写
return NextResponse.rewrite(url, {});
}
Matcher(匹配器)
用于过滤中间件以便在特定路径上运行,可以是数组或者字符串;方法名称config
/**
* 配置对象,用于定义匹配规则。
*
* @property {string[]} matcher - 匹配规则数组,用于屏蔽特定的URL路径。
* 该规则排除了包含"api"、"_next/static"、"_next/image"或"favicon.ico"的路径。
*/
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};
export const config = {
matcher: ["/home"],
};
export const config = {
matcher: "/home",
};
匹配器的值必须是以/开头的常量,方便构建时进行静态分析