Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Next.js Edge Runtime vs Node.js Runtime: Limits, Latency, and Use Cases

Edge gives near-zero cold starts and Web APIs only; Node gives sockets, files, and a fixed region. Why database work belongs on Node, and what fails at build time.

~5 min readNext.js
#Next.js#Edge Runtime#Deployment#Performance
3D illustration of a split platform with globe edge nodes on one side and a server rack on the other

Quick Summary

Next.js runs application code in one of two runtimes, chosen per route: the Node.js runtime (default) and the Edge runtime. The Edge runtime is a stripped V8 isolate with Web-standard APIs — fetch, Request, Response, crypto.subtle, TextEncoder, streams — and no filesystem, no native modules, no child_process, no net, and no arbitrary process access.

The choice is about cold start and location, not speed. A Node route on a serverless platform starts in hundreds of milliseconds and can be pinned to one region; an Edge route starts in tens of milliseconds and runs near the user, which matters for anything on the critical path of a page: middleware, cookie checks, geo redirects, A/B assignment, signed-URL generation.

Everything that talks to a database belongs on Node. Drivers such as pg, mysql2, better-sqlite3, and most ORMs use TCP sockets the Edge runtime does not provide, and Prisma needs a separate Edge-compatible client and usually an accelerator.

Basic Syntax & Core Signatures

ts
// app/api/geo/route.ts — Edge: read geolocation, no database export const runtime = "edge"; export const dynamic = "force-dynamic"; export async function GET(req: Request) { const country = req.headers.get("x-vercel-ip-country") ?? "US"; const city = req.headers.get("x-vercel-ip-city") ?? "unknown"; return Response.json({ country, city }, { headers: { "cache-control": "private, max-age=0, must-revalidate" }, }); }
ts
// app/api/report/route.ts — Node: filesystem, heavy SDK, database export const runtime = "nodejs"; export const maxDuration = 60; import { writeFile } from "node:fs/promises"; import { db } from "@/lib/db"; export async function POST(req: Request) { const rows = await db.order.findMany({ where: { status: "open" } }); await writeFile("/tmp/report.json", JSON.stringify(rows)); return Response.json({ count: rows.length }); }
ts
// app/api/webhook/route.ts — Edge with waitUntil for post-response work import { waitUntil } from "@vercel/functions"; export const runtime = "edge"; export async function POST(req: Request) { const body = await req.json(); waitUntil(logToQueue(body)); // runs after the response is sent return new Response("ok"); }

Runtime can be declared in a layout.tsx or page.tsx for a subtree, but a leaf route's own declaration wins. Setting it in the root layout to edge and then trying to use fs in one route produces a build-time error rather than a runtime surprise, which is the good outcome.

Key Comparison Table

CapabilityEdge runtimeNode.js runtime
fetch, Request, Response, streamsYesYes
crypto.subtle, TextEncoder, URLYesYes
TCP sockets, database drivers (pg, mysql2)NoYes
fs, path, child_process, netNoYes
Native modules (.node binaries)NoYes
Bundle size limit (Vercel)1 MB free / 4 MB paid250 MB unzipped
Cold start~10–50 ms~250 ms–1 s
Execution regionNearest to the userPinned region(s)
Max duration (default)30 s (platform dependent)10 s hobby, configurable
process.env dynamic accessNo, literal names onlyYes
waitUntil for background workYesYes
Streaming responsesYesYes
ISR / static generationNot for pages; revalidate unsupported on edge pagesYes
Use caseRuntimeReason
Middleware / proxy.tsEdge (fixed)Runs before routing for every request
Auth cookie verification with joseEdgeWeb Crypto, tiny dependency
Geo or locale redirectEdgeNeeds request headers close to the user
Database queriesNodeTCP sockets required
File generation, PDFs, image processingNodefs, sharp
AI SDK streaming with a hosted APIEitherEdge gives lower first-token latency
Cron reports with a 60 s budgetNodeLonger duration on the Node runtime

Practical Edge Cases & Deep Dives

1. The dependency that compiles but fails at runtime

A package that requires fs inside a try block builds for Edge (the bundler inlines a shim) and then throws at request time. The symptoms are vague: TypeError: Cannot read properties of undefined inside a library you do not own. Check before deploying:

bash
# List Node built-ins referenced by the dependency tree of an edge route npx esbuild app/api/geo/route.ts --bundle --platform=neutral --external:next \ --log-level=warning --outfile=/tmp/out.js 2>&1 | head -20

Practical substitutions: bcrypt → bcryptjs or Web Crypto PBKDF2, jsonwebtoken → jose, uuid (v4 via crypto) → crypto.randomUUID(), buffer → TextEncoder/atob.

2. Database access from the Edge: what is actually possible

HTTP-based drivers work because they use fetch: Neon's serverless driver over HTTP, PlanetScale's @planetscale/database, Turso's @libsql/client/web, and Supabase's REST or supabase-js with fetch. Anything opening a raw TCP connection does not. Even with an HTTP driver, per-query round trips from an edge location to a single-region database usually lose to a Node function next to the database — measure before moving queries to the Edge.

3. process.env and dynamic keys

Edge environment variables are substituted at build time from the variables the bundler can see. Literal access works; computed access does not.

ts
const key = process.env.API_KEY; // inlined const dynamic = process.env[someName]; // undefined on Edge

If configuration really is dynamic, pass it in the request (header, body) or read it from a service call, not from a computed env lookup.

4. Region pinning and latency

A Node function runs in its configured region; an Edge function runs near the user. For a page that queries a database in us-east-1, an Edge function in Seoul adds a trans-Pacific round trip per query. The fix is not "move to Node" by default but "put the database call in a Node function in the same region and keep the Edge function for header work". Splitting one route into an Edge gate plus a Node action is usually the right shape.

5. Streaming and waitUntil

Both runtimes stream. On the Edge, TransformStream is the idiomatic way to wrap an upstream stream, and waitUntil lets logging or analytics finish after the response:

ts
export const runtime = "edge"; export async function GET() { const upstream = await fetch("https://api.example.com/events"); const stream = upstream.body!.pipeThrough(new TransformStream({ transform(chunk, controller) { controller.enqueue(chunk); }, })); return new Response(stream, { headers: { "content-type": "text/event-stream" } }); }

On serverless Node, waitUntil is platform-provided (@vercel/functions); on a long-running server it is unnecessary because the process outlives the response.

Streaming from the Edge also changes error handling: once the first chunk is sent, the status code is fixed. A failure halfway through the stream cannot become a 500, so send errors as an in-stream event (an SSE event: error payload) and let the client decide what to show. That contract has to be written down for whoever consumes the endpoint.

6. Pages that cannot be static on the Edge

export const runtime = "edge" on a page disables ISR and generateStaticParams-based prerendering on platforms that only pre-render at build time on Node. If a page needs revalidate = 3600, keep it on Node. Pages whose only Edge benefit is a cookie read should use middleware for the redirect and stay Node for rendering.

Common Runtime & Configuration Mistakes

SymptomCauseFix
Build error: module not found fsNode built-in pulled in by a dependencyReplace the dependency or switch the route to nodejs
TypeError inside a library at request timeLibrary expects Node internalsUse the Web-standard equivalent
process.env.X undefined on EdgeDynamic key accessLiteral property access, or pass the value in
Edge function slow on every requestDatabase round trip across regionsMove the query into a Node route in the database's region
ISR silently not workingruntime = "edge" on a pageRemove it; keep prerendering on Node
Bundle exceeds the Edge limitLarge SDK imported for one callImport only the submodule, or move to Node
Middleware importing a Node packageFixed Edge runtimeKeep middleware dependency-free; verify only, fetch data elsewhere

Try matching browser tools

All tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.