我创建了一个新鲜的Next.js using 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 安装,我需要做任何配置吗?
注意:我将在此处执行一些 cookie 逻辑中间件用于身份验证。截屏:
![enter image description here](https://i.stack.imgur.com/EVSEM.png)
这是正常的,因为middleware
默认情况下,每个请求都会运行,包括获取 JavaScript、CSS 和图像文件等资源的请求。正如您可以在doc:
中间件将被调用您项目中的每条路线。以下是执行顺序:
-
headers
from next.config.js
-
redirects
from next.config.js
- 中间件 (
rewrites
, redirects
, etc.)
-
beforeFiles
(rewrites
) from next.config.js
- 文件系统路由(
public/
, _next/static/
, pages
, etc.)
-
afterFiles
(rewrites
) from next.config.js
- 动态路线(
/blog/[slug]
)
-
fallback
(rewrites
) from next.config.js
如果您添加一个console.log(request.nextUrl.pathname)
,您会看到它运行的不同路径。要让它仅对某些路径执行,您需要使用条件语句 or the 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).*)',
],
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)