跳到主要內容

middleware.js

middleware.js|ts 檔案用於編寫 Middleware (中介層),並在請求完成之前於伺服器上執行程式碼。然後,根據傳入的請求,您可以透過重寫、重新導向、修改請求或回應標頭,或直接回應來修改回應。

Middleware (中介層) 在路由渲染之前執行。它對於實作自訂伺服器端邏輯(例如身份驗證、記錄或處理重新導向)特別有用。

在專案根目錄中使用 middleware.ts (或 .js) 檔案來定義 Middleware (中介層)。例如,與 apppages 相同的層級,或在 src 內部(如果適用)。

middleware.ts
import { NextResponse, NextRequest } from 'next/server'
 
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
  return NextResponse.redirect(new URL('/home', request.url))
}
 
export const config = {
  matcher: '/about/:path*',
}

匯出

Middleware 函式

該檔案必須匯出單一函式,可以是預設匯出或命名為 middleware。請注意,不支援從同一個檔案匯出多個 middleware (中介層)。

middleware.js
// Example of default export
export default function middleware(request) {
  // Middleware logic
}

Config 物件 (選用)

選擇性地,可以與 Middleware (中介層) 函式一起匯出 config 物件。此物件包含 matcher (匹配器),用於指定 Middleware (中介層) 應用於哪些路徑。

Matcher (匹配器)

matcher (匹配器) 選項可讓您針對特定路徑,以便 Middleware (中介層) 在這些路徑上執行。您可以使用幾種方式指定這些路徑

  • 對於單一路徑:直接使用字串來定義路徑,例如 '/about'
  • 對於多個路徑:使用陣列列出多個路徑,例如 matcher: ['/about', '/contact'],這會將 Middleware (中介層) 應用於 /about/contact

此外,matcher (匹配器) 透過正規表示式支援複雜的路徑規範,例如 matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],從而能夠精確控制要包含或排除的路徑。

matcher (匹配器) 選項也接受包含以下鍵的物件陣列

  • source:用於匹配請求路徑的路徑或模式。它可以是字串,用於直接路徑匹配,或是模式,用於更複雜的匹配。
  • regexp (選用):正規表示式字串,用於根據來源微調匹配。它提供對包含或排除哪些路徑的額外控制。
  • locale (選用):布林值,設定為 false 時,會在路徑匹配中忽略基於語系的路由。
  • has (選用):根據特定請求元素(例如標頭、查詢參數或 Cookie)的存在指定條件。
  • missing (選用):著重於缺少某些請求元素(例如缺少標頭或 Cookie)的情況。
middleware.js
export const config = {
  matcher: [
    {
      source: '/api/*',
      regexp: '^/api/(.*)',
      locale: false,
      has: [
        { type: 'header', key: 'Authorization', value: 'Bearer Token' },
        { type: 'query', key: 'userId', value: '123' },
      ],
      missing: [{ type: 'cookie', key: 'session', value: 'active' }],
    },
  ],
}

Params (參數)

request (請求)

在定義 Middleware (中介層) 時,預設匯出函式接受單一參數 request (請求)。此參數是 NextRequest 的實例,代表傳入的 HTTP 請求。

middleware.ts
import type { NextRequest } from 'next/server'
 
export function middleware(request: NextRequest) {
  // Middleware logic goes here
}

要知道:

  • NextRequest 是一種型別,代表 Next.js Middleware (中介層) 中傳入的 HTTP 請求,而 NextResponse 是一個類別,用於操作和傳送回 HTTP 回應。

NextResponse

Middleware (中介層) 可以使用 NextResponse 物件,它擴展了 Web Response API。透過傳回 NextResponse 物件,您可以直接操作 Cookie、設定標頭、實作重新導向和重寫路徑。

要知道:對於重新導向,您也可以使用 Response.redirect 而不是 NextResponse.redirect

執行階段

Middleware (中介層) 僅支援 Edge runtime (邊緣執行階段)。無法使用 Node.js runtime (Node.js 執行階段)。

版本歷史

版本變更
v13.1.0新增進階 Middleware (中介層) 旗標
v13.0.0Middleware (中介層) 可以修改請求標頭、回應標頭和傳送回應
v12.2.0Middleware (中介層) 已穩定,請參閱升級指南
v12.0.9在 Edge Runtime (邊緣執行階段) 中強制執行絕對 URL (PR)
v12.0.0新增 Middleware (中介層) (Beta)