首页  >  问答  >  正文

为什么 Next.js 中间件会执行多次?

我使用 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 逻辑以进行身份​​验证。截图:

P粉448346289P粉448346289261 天前389

全部回复(1)我来回复

  • P粉950128819

    P粉9501288192024-01-05 09:12:41

    这是正常现象,因为中间件默认会针对每个请求运行,包括用于获取 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: '/',
    }

    回复
    0
  • 取消回复