Next.js Edge Runtime: Limits, APIs, and Patterns
The Edge runtime executes your code in data centers spread around the world, close to the user, with cold starts measured in single-digit milliseconds. That geography is the entire pitch: a JWT check that takes 40 ms of round-trip time against a single-region Node server becomes 2 ms when the same check runs in the edge location already serving the request. The price is a sandbox that resembles a browser more than a server â Web APIs instead of Node built-ins, no native modules, and a tight CPU and memory budget per invocation.
This lesson explains what the Edge runtime actually provides, which common Next.js operations break inside it, the libraries that were rebuilt for it, and the decision rule for choosing Edge versus Node per route.
Prerequisites
- !Understanding of Next.js route segment config
- !Comfort with async JavaScript and Web APIs
- !Experience with middleware or route handlers
What You'll Learn
- 1Declare Edge runtime for middleware, pages, and route handlers
- 2Identify Node-only code that fails on Edge and find replacements
- 3Use edge-compatible JWT and database libraries
- 4Decide per route whether Edge or Node is the right runtime
What the runtime actually is
Edge in Next.js means V8 isolates running a build of the runtime aligned with WinterCG standards. You get the Request and Response objects, fetch, URL, TextEncoder, crypto.subtle, Web Streams, and a handful of other Web platform APIs. You do not get fs, net, child_process, or the ability to load a package with a native binding. The sandbox also enforces limits on execution time and memory per invocation, so a runaway loop fails fast instead of pinning a server.
// app/api/edge-time/route.js
export const runtime = 'edge';
export async function GET(request) {
const { searchParams } = new URL(request.url);
const tz = searchParams.get('tz') ?? 'UTC';
const now = new Intl.DateTimeFormat('en-US', {
timeZone: tz,
dateStyle: 'full',
timeStyle: 'long',
}).format(new Date());
return Response.json({ timezone: tz, now });
}
This route carries almost no compute: it formats a date and returns JSON. That is the profile Edge loves â small functions that would otherwise pay network latency to a distant origin.
Declaring the runtime
Route segment config picks the runtime for a page, layout, or route handler. Middleware runs on Edge by default and does not need the export, though you can be explicit for clarity.
// app/api/search/route.js
export const runtime = 'edge';
export const dynamic = 'force-dynamic';
export async function GET(request) {
const { searchParams } = new URL(request.url);
const q = searchParams.get('q')?.trim() ?? '';
if (q.length < 2) {
return Response.json({ error: 'Query too short' }, { status: 400 });
}
const results = await searchIndex.query(q, { limit: 10 });
return Response.json({ query: q, results });
}
The build output labels each route with its runtime. Checking that table after a deploy catches accidental Node routes that slipped past review, and equally catches Edge routes you meant to keep on Node.
Node APIs that break, and their replacements
The most common failures are silent in development and loud in production: a package that detects the environment and ships different builds, a database driver that opens a TCP socket, or a helper that imports path for no functional reason. The replacement ecosystem is mature for the frequent cases.
| Node API or pattern | Why it fails on Edge | Edge-compatible replacement |
|---|---|---|
| crypto.sign, createHmac | Node crypto module absent | jose, Web Crypto via crypto.subtle |
| pg, mysql2 TCP drivers | No raw sockets allowed | Neon HTTP driver, Prisma Accelerate, Turso |
| fs and path modules | No filesystem | Environment variables, remote config, KV |
| Buffer.from for bytes | Buffer not defined | TextEncoder and Uint8Array |
| process.env access at odd times | Env inlined at build | Read env in the module scope you control |
| native modules with bindings | Cannot load outside V8 | Pure-JS equivalents or move route to Node |
// lib/auth-edge.js â Edge-safe JWT verification
import { jwtVerify } from 'jose';
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
export async function verify(token) {
const { payload } = await jwtVerify(token, secret, {
algorithms: ['HS256'],
});
return payload;
}
jose is the reference example: the same library that uses Node crypto under the hood detects the platform and switches to crypto.subtle when running in an isolate. Prefer libraries that ship this kind of dual build over hand-rolling crypto calls.
Edge-safe data access
Querying a traditional TCP database is the operation most likely to force a route back to Node. Three patterns keep data access on Edge. Serverless HTTP drivers speak SQL over HTTPS, trading a small per-query overhead for socket-free operation. Cache APIs and KV stores answer reads in single-digit milliseconds when the data tolerates eventual consistency. And for the cases where only the TCP driver will do, keep the route on Node and let the surrounding middleware stay on Edge â mixing runtimes across the request path is normal.
// app/api/profile/route.js using an HTTP database driver
import { neon } from '@neondatabase/serverless';
export const runtime = 'edge';
const sql = neon(process.env.DATABASE_EDGE_URL);
export async function GET(request) {
const { searchParams } = new URL(request.url);
const id = searchParams.get('id');
if (!id) {
return Response.json({ error: 'id required' }, { status: 400 });
}
const rows = await sql`SELECT id, name, plan FROM users WHERE id = ${id}`;
if (rows.length === 0) {
return Response.json({ error: 'not found' }, { status: 404 });
}
return Response.json({ user: rows[0] });
}
Notice the tagged-template API: the driver parameterizes values automatically, so the query is safe from injection without manual placeholder management.
Bodies, streaming, and the per-invocation budget
Edge isolates impose a memory ceiling on the request and response body as well as a CPU budget on execution. A route that reads an entire multi-megabyte upload into memory before processing it will hit that ceiling long before a comparable Node route would. The fix is to stop buffering: stream the request body through when you are transforming or proxying it, and stream the response out when the payload is large. Web Streams make this natural in the Edge runtime, since Request and Response already expose body as a ReadableStream.
The same budget shapes error handling. A long-running query against a distant region can consume most of the invocation window before your code gets a chance to respond. Timeouts should be set on outbound fetches inside the route with an explicit abort, so a slow upstream produces a clean 504-shaped response rather than an isolate termination that the platform reports as an internal error with no stack. Keep fallbacks small and cached; a recovery path that itself makes three slow calls simply dies in the same way.
Finally, remember that isolates are disposable. Anything you would have kept in a process-level variable â a warm connection object, an in-memory rate-limit map, a memoized config â vanishes between invocations. Design for statelessness: read configuration from environment variables or a remote key-value store, and keep counters in a shared store that survives the isolate. The reward for this discipline is horizontal scaling by default, since any isolate in any region can serve the next request without a warm-up ritual.
Choosing Edge or Node per route
The decision is rarely global. Global middleware benefits almost everyone because every request passes through it and the logic is light. An image-transformation endpoint that needs sharp must stay on Node. A personalized dashboard that queries a TCP-only database over a chatty ORM probably belongs on Node as well, because the per-invocation latency budget is unforgiving.
A practical rubric: if the route does authentication, A-B bucketing, geo-routing, header manipulation, or light fetch composition, Edge is likely a win. If it uses native libraries, long-running compute, streaming responses measured in minutes, or a TCP database driver, Node is the honest choice. Measure both when the route sits on a hot path; cold-start numbers and per-invocation CPU limits make benchmarks in staging essential.
â ī¸CPU time limits
Edge invocations have strict CPU budgets. A route that transforms a large payload or parses a multi-megabyte body can exceed the limit and fail under exactly the traffic spikes you planned for. Profile with production-sized inputs.
Common Mistakes
Assuming Edge means faster for every route
Fix: Edge wins when latency to the user dominates; heavy compute or TCP database access usually favors Node.
Importing a Node-only ORM into an Edge route and debugging a cryptic bundler error
Fix: Use an HTTP driver, Accelerate, or move the route to the Node runtime.
Relying on Buffer in shared utilities
Fix: Refactor utilities to TextEncoder and Uint8Array so they run in both runtimes.
Putting large image or PDF processing on Edge to save a few milliseconds
Fix: Keep native-module workloads on Node; reserve Edge for lightweight, latency-sensitive logic.
Best Practices
- Keep global middleware on Edge; decide the runtime per data-heavy route
- Standardize on dual-build libraries such as jose for shared auth code
- Verify the build output route table labels every route with the runtime you intended
- Benchmark staging traffic with realistic payloads before committing a hot path to Edge
Interview Questions
Q1: Name three things unavailable in the Edge runtime.
Node built-in modules such as fs, net, and child_process; native addon packages; and the long CPU budgets that Node routes enjoy.
Q2: How do you verify a JWT on Edge?
With the jose library using crypto.subtle, explicitly pinning the algorithm and comparing issuer and audience claims.
Q3: Can middleware and a page use different runtimes?
Yes. Middleware runs on Edge by default while the page can opt into Node; each segment declares its own runtime independently.
Key Takeaways
- Edge runtime is a WinterCG-aligned isolate with Web APIs and no Node built-ins.
- Middleware already runs there; pages and route handlers opt in with segment config.
- jose, HTTP database drivers, and TextEncoder cover the most common porting work.
- Match the runtime to the route: Edge for latency-sensitive light work, Node for native modules and heavy compute.
- Check the build output so every route's runtime matches your intent.