Next.js 可以在两个运行时中运行服务器代码。Node.js 运行时(默认)是完整的 Node 环境;Edge 运行时是一个轻量级、基于 V8 的环境,在全球分布式的边缘位置运行,靠近用户。
选择运行时
ts
// per route handler / page
export const runtime = "edge"; // or "nodejs" (the default)
Node.js runtime Edge runtime
────────────────────────────────────────────────────────────────
APIs full Node (fs, crypto, Web APIs only (fetch,
Buffer, native modules) Request/Response) — limited
npm packages all only those without Node APIs
Cold start slower, heavier near-zero, lightweight
Location regional (one region) global (near the user)
Latency to user higher if far away very low (geo-distributed)
Execution limits longer, more memory short CPU time, less memory
Database direct TCP connections HTTP-based DBs only (no raw TCP)
✓ Middleware (auth checks, redirects, geo-routing) — must be fast & global
✓ Simple, latency-sensitive endpoints (personalization, A/B, feature flags)
✓ Reading geolocation/headers to tailor responses
Edge 非常适合从靠近用户受益的轻量级逻辑以及即时冷启动。
✓ Direct database connections (Prisma over TCP, etc.)
✓ Heavy computation, large dependencies, native modules
✓ Anything using Node-specific APIs (fs, crypto.randomBytes via Node, Buffer)
export const runtime = "edge";
import fs from "fs"; // ❌ not available on Edge — build/runtime error
import { PrismaClient } from "@prisma/client"; // ⚠️ needs HTTP/data-proxy on Edge
许多流行库(包括打开原始数据库套接字的 ORM)在没有基于 HTTP 的适配器的情况下在 Edge 上无法工作——这是一个常见的陷阱。
选择运行时是一个真正的架构决策:Edge 用于快速、全球、轻量级逻辑(特别是中间件)且冷启动最少,Node.js 用于完整 API 访问、直接数据库连接和繁重工作。
了解 Edge 的局限性(仅限 Web API、无原始 TCP、执行时间短)可以防止频繁犯的错误——将数据库密集型或依赖 Node 的代码放在无法支持它的运行时上。