我使用 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 邏輯以進行身份驗證。截圖:
這是正常現象,因為
中間件
預設會針對每個請求運行,包括用於取得 JavaScritp、CSS 和映像檔等資源的請求。正如您可以在 doc 中閱讀的那樣:如果您記錄
request.nextUrl.pathname
,您將看到它運行的不同路徑。要讓它只對某些路徑執行,您需要使用條件語句 或matcher
對象,如下所示: