我使用 npx create-next-app@latest --typescript 创建了一个新的 Next.js。安装后(版本为13.3.4),在不更改任何文件的情况下,我在src文件夹内添加了一个新的middleware.ts文件,并且我只放置了这段代码:
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
export function middleware(request: NextRequest) {
console.log("request", request.nextUrl.pathname);
return NextResponse.next();
}
// EDIT: By putting this block will get expected result.
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).*)',
],
};
控制台日志被多次点击。我想应该是一次吧?对于这个新的 Next.js 安装,我需要做任何配置吗?
注意:我将在中间件中执行一些 cookie 逻辑以进行身份验证。截图:
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这是正常现象,因为
中间件默认会针对每个请求运行,包括用于获取 JavaScritp、CSS 和图像文件等资源的请求。正如您可以在 doc 中阅读的那样:如果您记录
request.nextUrl.pathname,您将看到它运行的不同路径。要让它仅对某些路径执行,您需要使用条件语句 或matcher对象,如下所示: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(); } // The above middleware would only run for the "/" path export const config = { matcher: '/', }