javascript - 为什么 Next.js 中间件会多次运行?

标签 javascript reactjs next.js

我创建了一个新的 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 逻辑。用于身份验证。截图:

enter image description here

最佳答案

这是正常现象,因为中间件默认会针对每个请求运行,包括用于获取 JavaScritp、CSS 和图像文件等资源的请求。正如您可以在 doc 上看到的那样:

Middleware will be invoked for every route in your project. The following is the execution order:

  1. headers from next.config.js
  2. redirects from next.config.js
  3. Middleware (rewrites, redirects, etc.)
  4. beforeFiles (rewrites) from next.config.js
  5. Filesystem routes (public/, _next/static/, pages, etc.)
  6. afterFiles (rewrites) from next.config.js
  7. Dynamic Routes (/blog/[slug])
  8. fallback (rewrites) from next.config.js

如果您添加console.log(request.nextUrl.pathname),您将看到它运行的不同路径。要让它仅对某些路径执行,您需要使用 conditional statementsmatcher配置,如下所示:

// 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/

相关文章:

php - 使用 JQuery 选择表单数组值

reactjs - Deck.gl 如何在点击时显示弹出窗口

ruby - 如何在 Hyperstack 中导入 Material 图标?

javascript - 购物车计数未正确更新

javascript - 将函数传递给 Angular Directive(指令)

javascript - 如何防止 tr 的背景颜色溢出到禁用的输入字段中

javascript - 如何将织物对象与旋转对齐?

javascript - undefined 不是一个对象(评估 _this2.props.navigation.navigate)

javascript - react 图像注释 - 语法错误 : Cannot use import statement outside a module

postgresql - Prisma 与 Bit.io 连接问题