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.

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
// 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" },
});
}// 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 });
}// 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
| Capability | Edge runtime | Node.js runtime |
|---|---|---|
fetch, Request, Response, streams | Yes | Yes |
crypto.subtle, TextEncoder, URL | Yes | Yes |
TCP sockets, database drivers (pg, mysql2) | No | Yes |
fs, path, child_process, net | No | Yes |
Native modules (.node binaries) | No | Yes |
| Bundle size limit (Vercel) | 1 MB free / 4 MB paid | 250 MB unzipped |
| Cold start | ~10–50 ms | ~250 ms–1 s |
| Execution region | Nearest to the user | Pinned region(s) |
| Max duration (default) | 30 s (platform dependent) | 10 s hobby, configurable |
process.env dynamic access | No, literal names only | Yes |
waitUntil for background work | Yes | Yes |
| Streaming responses | Yes | Yes |
| ISR / static generation | Not for pages; revalidate unsupported on edge pages | Yes |
| Use case | Runtime | Reason |
|---|---|---|
Middleware / proxy.ts | Edge (fixed) | Runs before routing for every request |
Auth cookie verification with jose | Edge | Web Crypto, tiny dependency |
| Geo or locale redirect | Edge | Needs request headers close to the user |
| Database queries | Node | TCP sockets required |
| File generation, PDFs, image processing | Node | fs, sharp |
| AI SDK streaming with a hosted API | Either | Edge gives lower first-token latency |
| Cron reports with a 60 s budget | Node | Longer 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:
# 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 -20Practical 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.
const key = process.env.API_KEY; // inlined
const dynamic = process.env[someName]; // undefined on EdgeIf 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:
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
| Symptom | Cause | Fix |
|---|---|---|
Build error: module not found fs | Node built-in pulled in by a dependency | Replace the dependency or switch the route to nodejs |
TypeError inside a library at request time | Library expects Node internals | Use the Web-standard equivalent |
process.env.X undefined on Edge | Dynamic key access | Literal property access, or pass the value in |
| Edge function slow on every request | Database round trip across regions | Move the query into a Node route in the database's region |
| ISR silently not working | runtime = "edge" on a page | Remove it; keep prerendering on Node |
| Bundle exceeds the Edge limit | Large SDK imported for one call | Import only the submodule, or move to Node |
| Middleware importing a Node package | Fixed Edge runtime | Keep middleware dependency-free; verify only, fetch data elsewhere |
Try matching browser tools
All toolsSmall utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Next.js guides
All Next.js guidesNext.js Static Export, Standalone Output, and Docker Deployment
Export has no server, standalone has a pruned one, and the default expects a full install. The three COPY lines that decide whether a container renders CSS.
Next.js Parallel Routes and Intercepting Routes: Slot Layouts and Modals
Named slots render several pages in one layout, and (.) interception makes a click open over the page while a direct link renders the full route. Why every slot needs default.tsx.
Next.js ISR: Route Revalidate, revalidateTag, and On-Demand Invalidation
Two clocks and one trigger: route revalidate seconds, fetch-level tags, and a webhook that calls revalidateTag. A timer is a ceiling on freshness, never a guarantee.
Next.js Environment Variables: NEXT_PUBLIC_, Build-Time Inlining, and Runtime Config
The prefix decides whether a value is compiled into the browser bundle or stays on the server. One image, two environments, and the choice that follows from it.
More in Next.js
All Next.js guidesThe guides filed next to this one in Next.js, in library order.