紀錄工作經驗、相關知識,解決技術相關問題。

Next

Next.js proxy.js 用法:取代 middleware 的 proxy 函式、matcher 設定與 Node.js runtime

Next.js proxy.js 用法:取代 middleware 的 proxy 函式、matcher 設定與 Node.js runtime 特色圖片

Next.js 的 proxy.js(TypeScript 專案寫成 proxy.ts)是在請求完成之前先執行的檔案:可以依請求內容轉址(redirect)、改寫(rewrite)、增減請求或回應標頭,或直接回一個回應。Next.js 16.0.0 起,原本的 middleware 檔案慣例已棄用並改名為 proxy,Proxy 也固定使用 Node.js runtime。本文以 Next.js 16(範例在 16.4.3、App Router 執行)說明 proxy.js 的檔案位置、匯出規則、matcher 設定,以及從 middleware 遷移時會遇到的錯誤訊息。

檔案位置與基本寫法

proxy.ts 放在專案根目錄,和 app 同一層;專案有用 src 資料夾時,放在 src 裡。每個專案只支援一個 proxy.ts,邏輯多的話可以拆成其他模組,再匯入到 proxy.ts。

my-app/
├─ app/
├─ proxy.ts        ← 這裡
├─ next.config.ts
└─ package.json

最基本的寫法:把 /about 底下的請求全部轉到 /home。

// proxy.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function proxy(request: NextRequest) {
  return NextResponse.redirect(new URL('/home', request.url))
}

export const config = {
  matcher: '/about/:path*',
}

匯出規則:

  • 檔案必須匯出單一函式,可以是具名匯出 proxy,也可以是 export default;同一個檔案不支援多個 proxy 函式。
  • config 是選用的匯出,主要用來放 matcher。
  • 函式收到兩個參數:request(NextRequest)與 event(NextFetchEvent),只宣告用得到的即可。event.waitUntil(promise) 讓背景工作在回應送出後繼續做完。

next build 成功後,路由表會多一行 ƒ Proxy (Middleware)。

matcher:限制 Proxy 的執行範圍

沒有設定 matcher 時,Proxy 會在每個請求執行,包含 _next/static 的靜態檔、_next/image 的圖片最佳化,以及 public/ 裡的資源。驗證或轉址邏輯可能連 CSS、JS、圖片都擋掉。

// 單一路徑
export const config = { matcher: '/about/:path*' }

// 多個路徑
export const config = { matcher: ['/about/:path*', '/dashboard/:path*'] }

// 排除特定路徑(負向前瞻)
export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)'],
}

路徑寫法的規則:

  • 必須以 / 開頭,並從路徑開頭比對:/about 會比對到 /about 與 /about/team,不會比對到 /blog/about。
  • :path 是具名參數,只吃一段:/about/:path 比對 /about/a,不比對 /about/a/c。
  • 具名參數後加 *(零或多段)、?(零或一段)、+(一或多段);/about/(.*) 等同 /about/:path*。

matcher 也可以寫成物件陣列,用 source 指定路徑,再用 has、missing 依標頭、query 或 cookie 決定要不要執行。matcher 的值必須是常數,因為 Next.js 在 build 時靜態分析它;寫成變數之類的動態值會被忽略。

轉址、改寫、直接回應與標頭

下面這份 proxy.ts 把四種常見用法放在一起,matcher 只比對 /demo/ 底下、但不是 /demo/skip 開頭的路徑:

// proxy.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

const base = '/demo'

export function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl

  // 1. 舊網址轉址
  if (pathname === `${base}/old`) {
    return NextResponse.redirect(new URL(`${base}/new`, request.url))
  }

  // 2. 依 cookie 改寫到 B 版,網址列不變
  if (pathname === `${base}/ab` && request.cookies.get('variant')?.value === 'b') {
    return NextResponse.rewrite(new URL(`${base}/ab-b`, request.url))
  }

  // 3. API 沒帶 token cookie 直接回 401
  if (pathname.startsWith(`${base}/api/`) && !request.cookies.has('token')) {
    return Response.json(
      { success: false, message: 'authentication failed' },
      { status: 401 }
    )
  }

  // 4. 加請求標頭給頁面讀,加回應標頭給瀏覽器
  const requestHeaders = new Headers(request.headers)
  requestHeaders.set('x-from-proxy', 'hello')
  const response = NextResponse.next({ request: { headers: requestHeaders } })
  response.headers.set('x-proxy-hit', pathname)
  return response
}

export const config = {
  matcher: ['/demo/((?!skip).*)'],
}

頁面用 headers() 讀 Proxy 加的請求標頭:

// app/demo/headers/page.tsx
import { headers } from 'next/headers'
import { Suspense } from 'react'

async function FromProxy() {
  const h = await headers()
  return <p>x-from-proxy:{h.get('x-from-proxy') ?? '(沒有)'}</p>
}

export default function Page() {
  return (
    <Suspense fallback={<p>讀取中…</p>}>
      <FromProxy />
    </Suspense>
  )
}

next build 後 next start,用 curl 送請求的結果:

GET /demo/old
HTTP/1.1 307 Temporary Redirect
location: /demo/new

GET /demo/ab(帶 Cookie: variant=b)
HTTP/1.1 200 OK            → 內容是 B 版頁面,網址仍是 /demo/ab

GET /demo/api/data(沒有 token)
HTTP/1.1 401 Unauthorized
{"success":false,"message":"authentication failed"}

GET /demo/api/data(帶 Cookie: token=abc)
HTTP/1.1 200 OK
x-proxy-hit: /demo/api/data
{"success":true,"data":[1,2,3]}

GET /demo/headers
HTTP/1.1 200 OK
x-proxy-hit: /demo/headers  → 頁面顯示「x-from-proxy:hello」

GET /demo/skip
HTTP/1.1 200 OK            → 沒有 x-proxy-hit,Proxy 沒執行

幾個細節:

  • 範例的 NextResponse.redirect() 沒指定狀態碼,回應是 307 Temporary Redirect。
  • 第 4 段的 x-from-proxy 只出現在頁面讀到的請求標頭,回應標頭裡沒有它。官方特別提醒要寫 NextResponse.next({ request: { headers } });寫成 NextResponse.next({ headers }) 會把這些標頭送給用戶端。
  • 第 3 段直接回 Response.json(),不會進到 Route Handler。

runtime 固定是 Node.js

Next.js 16 的 Proxy 預設使用 Node.js runtime,而且不能設定 runtime。在 proxy.ts 的 config 加上 runtime: 'edge',next build 直接失敗:

./proxy.ts:35:14
Error: Next.js can't recognize the exported `config` field in route. Proxy does not support Edge runtime.

官方的 Next.js 16 升級說明寫明:需要繼續用 Edge runtime 的專案,就先保留 middleware。

從 middleware 遷移到 proxy

官方說明改名是因為「middleware」容易和 Express.js 的 Middleware 混淆,「proxy」較能表達它是應用程式前方的網路邊界。

遷移只有兩步:檔名 middleware.ts 改成 proxy.ts,匯出的函式名 middleware 改成 proxy。官方也提供 codemod 一次改好:

npx @next/codemod@canary middleware-to-proxy .
// middleware.ts -> proxy.ts
- export function middleware() {
+ export function proxy() {

名稱含 middleware 的設定也一起改名,例如 next.config 的 skipMiddlewareUrlNormalize 改為 skipProxyUrlNormalize。實際對含 middleware.ts 的專案執行 codemod(@next/codemod 16.5.0-canary.40),它會把檔案改名為 proxy.ts、函式改名為 proxy,next.config.ts 裡的 skipMiddlewareUrlNormalize 也一併改成 skipProxyUrlNormalize。

在 Next.js 16.4.3 用三種狀態跑 next build,訊息分別如下:

只有舊的 middleware.ts:build 成功,但出現棄用警告:

⚠ The "middleware" file convention is deprecated. Please use "proxy" instead.

  To migrate automatically, run:
  npx @next/codemod@canary middleware-to-proxy .

middleware.ts 與 proxy.ts 同時存在:build 失敗:

Error: Both middleware file "./middleware.ts" and proxy file "./proxy.ts" are detected. Please use "./proxy.ts" only.

檔名改成 proxy.ts,函式還叫 middleware:build 失敗:

Error: Proxy is missing expected function export name
...
To fix it:
- Ensure this file has either a default or "proxy" function export.

第三種是手動改名最常漏的。官方建議就算用 export default,函式也命名為 proxy。

舊版 middleware.ts 的寫法可參考〈Next.js Middleware:掌握請求攔截與修改〉,照本節改檔名與函式名即可。

使用時要注意的地方

  • 執行順序:next.config 的 headers → redirects → Proxy → beforeFiles rewrites → 檔案系統路由(public/、app/ 等)→ afterFiles rewrites → 動態路由 → fallback rewrites。
  • 單純轉址先用 next.config 的 redirects:要讀請求資料或邏輯較複雜時才用 Proxy。
  • 不要在 Proxy 做慢速資料抓取,也不要把它當成完整的 session 管理或授權方案;它適合做「沒登入就先轉到登入頁」這種樂觀檢查。fetch 的 cache、next.revalidate、next.tags 選項在 Proxy 裡沒有作用。
  • Server Function 不能只靠 Proxy 驗證:Server Function 以 POST 送到使用它的路由,matcher 排除的路徑上的 Server Function 也不經過 Proxy,官方建議在每個 Server Function 內檢查驗證與授權,寫法可參考〈Next.js use server 指令用法〉。
  • 不要靠共用模組或全域變數傳資料:Proxy 與渲染程式分開執行,要傳資訊給應用程式,用標頭、cookie、rewrite、redirect 或網址。
  • 部署限制:Static export 不支援 Proxy。

參考資料與延伸閱讀

發佈留言