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 的定位已經改變,官方文件的說法如下:
experimental-edge的棄用:Next.js v15.0.0-RC 棄用export const runtime = 'experimental-edge',官方提供 Codemod 轉換成'edge'。'edge'標為 deprecated:Route Segment Config 文件把runtime的型別寫成'nodejs' | 'edge' (deprecated),預設值是'nodejs'。官方的遷移說明是:移除runtime匯出即可,Node.js 為預設,不需要替代設定;適用於page.ts、layout.ts、route.ts與 API routes。- Next.js 16.3 與 Vercel:Vercel 文件寫道,從 Next.js 16.3 開始不再支援設定
runtime = 'edge',路由與頁面會在 Node.js 執行。 - 啟用 Cache Components 時:必須移除
runtime匯出(包含nodejs)。原本用runtime = 'edge'的路由刪除該匯出後,需要 edge 行為時改用 Proxy。 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
解法
- 移除 Node.js 專有模組:改用 Web 標準 API。例如處理二進位資料時使用
Uint8Array/Blob/ArrayBuffer,需要遠端資源時使用fetch()。 - 移除
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。
解法
- 移除
runtime = 'edge':路由改回預設的 Node.js Runtime,就能使用原本的資料庫驅動程式。這也是官方遷移說明建議的方向。 - 確實要留在 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 的快取行為。
解法
- 需要 ISR:移除
export const runtime = 'edge',使用預設的 Node.js Runtime。 - 只需要讓 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 判斷〉 參閱實作細節。
參考資料與延伸閱讀
- Next.js: Edge Runtime
- Next.js: Route Segment Config
- Next.js: Edge Runtime Deprecated
- Next.js: instrumentation.js
- Next.js: Migrating to Cache Components
- Vercel: Edge Runtime
- Cloudflare Workers: Next.js
- Cloudflare Workers: Bindings
- Cloudflare Workers: TCP sockets
- GitHub: cloudflare/next-on-pages
- MDN: Cache-Control
- 站內延伸閱讀:〈Next.js Pages Router 載入順序解析:middleware、_app 與 _document 差異與作用〉
發佈留言