我创建了一个新的 Next.js使用npx create-next-app@latest --typescript
。安装后(版本为 13.3.4
),在不更改任何文件的情况下,我添加了新的 middleware.ts
src
内的文件文件夹,我只放了这段代码:
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
export function middleware(request: NextRequest) {
console.log("request", JSON.stringify(request));
return NextResponse.next();
}
控制台日志被多次点击。我想应该是一次吧?对于这个新的 Next.js 安装,我需要做任何配置吗?
注意:我将在 middleware 中执行一些 cookie 逻辑。用于身份验证。截图:
最佳答案
这是正常现象,因为中间件
默认会针对每个请求运行,包括用于获取 JavaScritp、CSS 和图像文件等资源的请求。正如您可以在 doc 上看到的那样:
Middleware will be invoked for every route in your project. The following is the execution order:
headers
fromnext.config.js
redirects
fromnext.config.js
- Middleware (
rewrites
,redirects
, etc.)beforeFiles
(rewrites
) fromnext.config.js
- Filesystem routes (
public/
,_next/static/
,pages
, etc.)afterFiles
(rewrites
) fromnext.config.js
- Dynamic Routes (
/blog/[slug]
)fallback
(rewrites
) fromnext.config.js
如果您添加console.log(request.nextUrl.pathname)
,您将看到它运行的不同路径。要让它仅对某些路径执行,您需要使用 conditional statements或matcher
配置,如下所示:
// middleware.ts
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
export function middleware(request: NextRequest) {
console.log("Request for : ", request.nextUrl.pathname);
return NextResponse.next();
}
export const config = {
// The above middleware would only run for the "/" path
matcher: '/',
}
另一个经常使用的匹配模式是这个:
// middleware.ts
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
export function middleware(request: NextRequest) {
console.log("Request for : ", request.nextUrl.pathname);
return NextResponse.next();
}
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).*)',
],
}
关于javascript - 为什么 Next.js 中间件会多次运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76164152/