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

Javascript, Next

export const runtime = ‘edge’ 設定教學:Next.js 報錯排查、Cloudflare 現況與棄用遷移

export const runtime = 'edge' 設定教學:Next.js 報錯排查、Cloudflare 現況與棄用遷移 特色圖片

export const runtime = 'edge' 是 Next.js 的 Route Segment Config 之一,用來指定 Route Segment(如 page.ts、route.ts 或 layout.ts)執行於 Edge Runtime。Next.js 官方文件目前將 runtime 的 'edge' 標為 deprecated,預設值是 'nodejs';本文先說明這個設定的寫法與限制,再整理遇到報錯時的處理方式與遷移方向。

想深入了解邊緣節點如何透過 CDN 加速降低網頁回應時間,可前往 〈CDN 降低 TTFB 與邊緣運算架構實踐:善用 Edge Computing 加速跨國網頁回應〉 觀看基礎原理。本文聚焦於 export const runtime = 'edge' 的語法、環境差異、資料庫連線限制、Cloudflare 部署現況以及 Next.js 的棄用遷移。

若需要直接跳轉複製常用宣告語法或查閱 Node.js 模組報錯,可點擊:


一、 核心語法速查與規格對照

在 Next.js(App Router)的 app/api/hello/route.ts 或 app/page.tsx 中宣告 Edge Runtime,只需導出 runtime 常數:

// app/api/hello/route.ts
import { NextResponse } from 'next/server';

// 指定該 API Route 或頁面於 Edge Runtime 執行
export const runtime = 'edge';

export async function GET(request: Request) {
  return NextResponse.json({
    message: 'Hello from Edge Runtime!',
    timestamp: new Date().toISOString(),
  });
}

Runtime 環境與規格特性對照

Next.js 有兩種伺服器 runtime:Node.js Runtime 是預設值,可使用所有 Node.js API;Edge Runtime 只提供一組較受限的 API。以下依 Next.js 官方文件整理兩者差異:

評估維度Edge Runtime (edge)Node.js Runtime (nodejs)
官方現況runtime 的 'edge' 標為 deprecated預設值
API 支援範圍受限的 API 集合,不支援所有 Node.js API可使用所有 Node.js API
檔案系統原生 Node.js API 不支援,例如無法讀寫檔案系統可使用 Node.js 的檔案系統 API

此外,官方文件列出的 Edge Runtime 注意事項還有:不支援 Incremental Static Regeneration(ISR);可以用 process.env 讀取環境變數;不允許直接呼叫 require;eval 與 new Function(evalString) 等動態程式碼執行會被停用。


二、 關鍵機制與跨情境細部拆解

1. 語法結構拆解:export const 與 export default 的編譯期差異

Next.js 官方文件說明,Route Segment Config 是「直接匯出(directly exporting)」指定名稱的變數。所以設定 runtime 要用具名匯出的 export const runtime = 'edge',不能寫在 export default 裡。

// 具名匯出:Next.js 依名稱 runtime 讀取設定
export const runtime = 'edge';

// 預設匯出是頁面元件本身,不是路由設定
export default function Page() {
  return <h1>Edge Page</h1>;
}
  • 預設匯出:export default 匯出的是頁面元件,把 { runtime: 'edge' } 包在預設匯出裡,Next.js 不會當成路由設定。下方 Q4 附有本機 Next.js 16.4.3 的執行結果。

2. export const runtime edge nextjs 的棄用與遷移

Edge Runtime 在 Next.js 的定位已經改變,官方文件的說法如下:

  1. experimental-edge 的棄用:Next.js v15.0.0-RC 棄用 export const runtime = 'experimental-edge',官方提供 Codemod 轉換成 'edge'。
  2. 'edge' 標為 deprecated:Route Segment Config 文件把 runtime 的型別寫成 'nodejs' | 'edge' (deprecated),預設值是 'nodejs'。官方的遷移說明是:移除 runtime 匯出即可,Node.js 為預設,不需要替代設定;適用於 page.ts、layout.ts、route.ts 與 API routes。
  3. Next.js 16.3 與 Vercel:Vercel 文件寫道,從 Next.js 16.3 開始不再支援設定 runtime = 'edge',路由與頁面會在 Node.js 執行。
  4. 啟用 Cache Components 時:必須移除 runtime 匯出(包含 nodejs)。原本用 runtime = 'edge' 的路由刪除該匯出後,需要 edge 行為時改用 Proxy。
  5. proxy.js 與 Middleware 的分工:官方升級到 Next.js 16 的文件寫道,proxy 不支援 edge runtime,runtime 固定為 nodejs 且不能設定;要繼續使用 edge runtime,就保留 middleware。關於 proxy.js 與 middleware 的權責切換細節,可參考 〈Next.js proxy.js 用法:取代 middleware 的 proxy 函式、matcher 設定與 Node.js runtime〉 的說明;關於兩者執行順序與載入機制,可參閱 〈Next.js Pages Router 載入順序解析:middleware、_app 與 _document 差異與作用〉。

以下是 Next.js 16.4.3(Windows 11)在專案開啟 cacheComponents、route.ts 內保留 export const runtime = 'edge' 時的 next dev 輸出:

⚠ The Edge Runtime is deprecated. You can use the "nodejs" runtime instead. Learn more: https://nextjs.org/docs/messages/edge-runtime-deprecated
⨯ ./app/tests/export-const-runtime-edge/edge-fs/route.ts:3:14
Error: Route segment config "runtime" is not compatible with `nextConfig.cacheComponents`. Please remove it.

關掉 cacheComponents 後,同一版本的 next dev 仍會依宣告在 Edge 執行(路由內讀到 process.env.NEXT_RUNTIME 為 edge)。

3. export const runtime edge cloudflare 部署現況

過去常見的做法是用 @cloudflare/next-on-pages 部署宣告 export const runtime = 'edge' 的 Next.js 路由。該套件的 GitHub 儲存庫現在標示套件已棄用、儲存庫已封存(2026 年 10 月 1 日起唯讀);Cloudflare Workers 的 Next.js 指南寫道,Cloudflare 建議以 vinext(目前為 beta)作為在 Workers 執行 Next.js 應用程式的預設方式,暫時無法遷移的 OpenNext 應用程式則可使用 OpenNext adapter。

Cloudflare 端的資源存取方式,依官方文件整理如下:

  • Bindings:bindings 位於 env 物件,可從 handler 的參數取得,或從 cloudflare:workers 匯入;在 Next.js 的 server components、route handlers 與 server actions 中使用 cloudflare:workers,bindings 定義在 Wrangler 設定檔,型別用 wrangler types 產生。程式寫法見下方 Q2。
  • 環境變數:可從 env 取得;搭配 nodejs_compat 與 nodejs_compat_populate_process_env 旗標時(相容日期 2025-04-01 之後預設啟用),也能從全域 process.env 讀取,且 process.env 會在第一次存取 process 時才填入。

三、 常見問題與排錯(Q&A)

Q1:在 Next.js 中設定 export const runtime = 'edge' 時,為什麼 import fs 會報錯?

問題原因

官方文件說明 Edge Runtime 不支援原生 Node.js API,例如無法讀寫檔案系統。Next.js 16.4.3 的 next dev 在 Edge 路由 import fs from 'node:fs/promises' 時,輸出的不是 Module not found: Can't resolve 'fs',而是警告加上 500 回應:

Warning: A Node.js module is loaded ('node:fs/promises' at line 1) which is not supported in the Edge Runtime.
    Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime
...
Error: Failed to load external module node:fs/promises: TypeError: Native module not found: node:fs/promises

解法

  1. 移除 Node.js 專有模組:改用 Web 標準 API。例如處理二進位資料時使用 Uint8Array / Blob / ArrayBuffer,需要遠端資源時使用 fetch()。
  2. 移除 runtime = 'edge',回到預設的 Node.js Runtime:若該路由必須讀檔或依賴 Node.js 專有套件,依官方遷移說明刪掉 runtime 匯出即可,Node.js 為預設,不需要替代設定。專案若開啟 Cache Components,連 export const runtime = 'nodejs' 也必須移除,所以不建議明確寫出 nodejs。
// app/api/local-file/route.ts
// 沒有 runtime 匯出,使用預設的 Node.js Runtime,可以引用 fs 模組
import fs from 'node:fs/promises';
import path from 'node:path';

export async function GET() {
  const filePath = path.join(process.cwd(), 'data.json');
  const fileData = await fs.readFile(filePath, 'utf-8');
  return Response.json(JSON.parse(fileData));
}

Q2:部署到 Cloudflare 時,環境變數與繫結 (Bindings) 要怎麼取得?

問題原因

Cloudflare Workers 的資源繫結(KV、D1、R2 等)不是從 .env 載入,而是放在 env 物件上,可從 handler 參數取得,或從 cloudflare:workers 匯入;process.env 的用法見第二節第 3 點。

過去常見的 @cloudflare/next-on-pages 與 getRequestContext() 寫法,對應的套件已棄用(見第二節第 3 點)。

解法

依 Cloudflare Next.js 指南,在 server components、route handlers 與 server actions 中從 cloudflare:workers 匯入 env,bindings 在 Wrangler 設定檔宣告,型別以 wrangler types 產生:

// app/api/d1-query/route.ts
import { env } from 'cloudflare:workers';

export async function GET() {
  // env.DB 為在 Wrangler 設定檔宣告的 D1 資料庫 binding
  const { results } = await env.DB.prepare('SELECT * FROM users LIMIT 10').all();

  return Response.json(results);
}

Q3:使用 export const runtime = 'edge' 後,pg 或 mysql2 這類資料庫客戶端為什麼會出問題?

問題原因

Next.js 官方文件寫明,Edge Runtime 不支援原生 Node.js API。pg、mysql2 這類驅動程式的連線實作建立在 Node.js 的網路模組上,放進 Edge Runtime 路由就可能因為用到不支援的 Node.js API 而失敗。

要區分「Next.js 的 Edge Runtime」與「Cloudflare Workers」:Workers 本身提供 connect() API 建立對外 TCP 連線,所以「Edge 一律不能做 TCP」並不正確,要看實際平台與驅動程式用到哪些 API。

解法

  1. 移除 runtime = 'edge':路由改回預設的 Node.js Runtime,就能使用原本的資料庫驅動程式。這也是官方遷移說明建議的方向。
  2. 確實要留在 Edge 或 Workers 的環境:改用以 fetch 呼叫資料庫服務 HTTP API 的做法,或是查閱所選資料庫與驅動程式的官方文件,確認它是否支援該平台。
// app/api/db-http/route.ts
// 透過 HTTP 呼叫資料庫服務提供的 API,不需要 Node.js 的網路模組
export async function GET() {
  const res = await fetch(process.env.DB_HTTP_ENDPOINT!, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ sql: 'SELECT NOW()' }),
  });

  return Response.json(await res.json());
}

Q4:export default { runtime: 'edge' } 為什麼不會生效?

問題原因

Route Segment Config 是直接匯出指定名稱的變數,Next.js 讀的是名稱為 runtime 的具名匯出。把設定包在 export default 的物件裡,Next.js 不會當成路由設定。

Next.js 16.4.3(關閉 cacheComponents)中,route.ts 寫成 export default { runtime: 'edge' },GET 回傳 process.env.NEXT_RUNTIME 的結果:

{"runtime":"nodejs"}

同一個專案裡,寫成 export const runtime = 'edge' 的路由回傳的是 {"runtime":"edge","ok":true}。

解法

改成具名匯出,或依官方遷移說明直接移除(Node.js 為預設):

// ❌ 無效:Next.js 不會讀取預設匯出裡的設定
export default {
  runtime: 'edge',
  dynamic: 'force-dynamic'
};

// ✅ 具名匯出(Next.js 16 已將 'edge' 標為 deprecated,新專案不需要這行)
export const runtime = 'edge';

Q5:同時使用 export const runtime = 'edge' 與 ISR 會有什麼問題?

問題原因

Next.js 官方文件寫明 Edge Runtime 不支援 Incremental Static Regeneration(ISR),所以搭配 export const revalidate = 60 這類設定,無法取得 ISR 的快取行為。

解法

  1. 需要 ISR:移除 export const runtime = 'edge',使用預設的 Node.js Runtime。
  2. 只需要讓 CDN 快取回應:可以在回應標頭自行設定 Cache-Control。依 MDN,s-maxage 指定回應在共用快取(shared cache)保持新鮮的時間,stale-while-revalidate 允許快取在背景重新驗證時重用過期的回應。實際會不會快取,取決於前面的 CDN 或部署平台怎麼處理。
// app/api/cache-header/route.ts
export async function GET() {
  const data = { time: new Date().toISOString() };

  return Response.json(data, {
    headers: {
      'Cache-Control': 'public, s-maxage=60, stale-while-revalidate=300',
    },
  });
}

Q6:如何用 instrumentation.ts 統一回報路由的執行錯誤?

問題原因

官方文件寫道,onRequestError 用來把伺服器錯誤送到自訂的觀測服務,從 v15.0.0 引入;instrumentation.js 在 Node.js 與 Edge runtime 都能運作,可用 process.env.NEXT_RUNTIME 區分。

解法

匯出 onRequestError,函式內有非同步工作要 await。官方文件提醒,error 不一定是原始丟出的錯誤實例,可用 digest 辨識。寫法如下:

// instrumentation.ts
import { type Instrumentation } from 'next';

export async function register() {
  // 伺服器啟動時只呼叫一次
}

export const onRequestError: Instrumentation.onRequestError = async (err, request, context) => {
  const message = err instanceof Error ? err.message : String(err);

  await fetch('https://example.com/report-error', {
    method: 'POST',
    body: JSON.stringify({ message, request, context }),
    headers: { 'Content-Type': 'application/json' },
  });
};

Next.js 16.4.3 的 next dev 中,一個丟出 Error('node boom') 的 Node.js Route Handler,傳給 onRequestError 的內容如下(NEXT_RUNTIME 為 nodejs):

{"rt":"nodejs","message":"node boom","request":{"path":"/tests/export-const-runtime-edge/node-throw","method":"GET"},"context":{"routerKind":"App Router","routePath":"/tests/export-const-runtime-edge/node-throw","routeType":"route"}}

同一個專案以 next build 與 next start 執行時,Edge 路由(runtime = 'edge')丟錯同樣會觸發 onRequestError,context.routeType 為 route;next dev 中只看到 Node.js 路由觸發。

想了解 instrumentation.ts 的完整設定與 NEXT_RUNTIME 環境變數判斷,請前往 〈Next.js instrumentation.js 用法:register() 啟動初始化、onRequestError 錯誤回報與 NEXT_RUNTIME 判斷〉 參閱實作細節。


參考資料與延伸閱讀

  1. Next.js: Edge Runtime
  2. Next.js: Route Segment Config
  3. Next.js: Edge Runtime Deprecated
  4. Next.js: instrumentation.js
  5. Next.js: Migrating to Cache Components
  6. Vercel: Edge Runtime
  7. Cloudflare Workers: Next.js
  8. Cloudflare Workers: Bindings
  9. Cloudflare Workers: TCP sockets
  10. GitHub: cloudflare/next-on-pages
  11. MDN: Cache-Control
  12. 站內延伸閱讀:〈Next.js Pages Router 載入順序解析:middleware、_app 與 _document 差異與作用〉

發佈留言