首頁  >  問答  >  主體

為什麼 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 天前386

全部回覆(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
  • 取消回覆