Skip to main content

Next.js Edge Runtime

Answer​

The Edge Runtime is a lightweight runtime that runs Next.js code at the edge (CDN locations closest to users), providing lower latency than traditional serverless functions.

Edge vs Node.js Runtime​

Using Edge Runtime​

// Route handlers
// app/api/hello/route.js
export const runtime = "edge";

export async function GET(request) {
return new Response("Hello from the Edge!");
}

// Middleware (always edge)
// middleware.js
export function middleware(request) {
// Runs at edge automatically
}

// Pages/Server Components
// app/page.js
export const runtime = "edge";

export default function Page() {
return <div>Edge-rendered page</div>;
}

Edge Limitations​

// ✅ Available at Edge
fetch()
Request, Response
URL, URLSearchParams
TextEncoder, TextDecoder
crypto
Streams
setTimeout, setInterval

// ❌ NOT available at Edge
fs (file system)
path
require() dynamic imports
Native Node.js modules
Most npm packages with native bindings
Full Node.js crypto (limited subset available)

When to Use Edge​

Use CaseRuntime
Auth checksEdge ✅
A/B testingEdge ✅
Geolocation routingEdge ✅
Simple API responsesEdge ✅
Database queriesNode.js ✅
File operationsNode.js ✅
Heavy computationNode.js ✅
Third-party SDKsNode.js ✅

Edge Functions Examples​

// Geolocation personalization
export const runtime = "edge";

export async function GET(request) {
const country = request.geo?.country || "US";
const city = request.geo?.city || "Unknown";

return Response.json({
message: `Hello from ${city}, ${country}!`,
country,
city,
});
}

// A/B Testing
export const runtime = "edge";

export function middleware(request) {
const bucket = Math.random() < 0.5 ? "control" : "experiment";

const response = NextResponse.next();
response.cookies.set("ab-bucket", bucket);

return response;
}

Edge with ORM/Database​

// Use edge-compatible database clients
import { PrismaClient } from "@prisma/client/edge";
import { withAccelerate } from "@prisma/extension-accelerate";

export const runtime = "edge";

const prisma = new PrismaClient().$extends(withAccelerate());

export async function GET() {
const users = await prisma.user.findMany({
cacheStrategy: { ttl: 60 },
});
return Response.json(users);
}

// Or use edge-native databases
// - Cloudflare D1
// - PlanetScale (HTTP)
// - Neon (HTTP)
// - Turso

Streaming from Edge​

export const runtime = "edge";

export async function GET() {
const encoder = new TextEncoder();

const stream = new ReadableStream({
async start(controller) {
for (let i = 0; i < 5; i++) {
await new Promise((r) => setTimeout(r, 1000));
controller.enqueue(encoder.encode(`Data ${i}\n`));
}
controller.close();
},
});

return new Response(stream, {
headers: { "Content-Type": "text/plain" },
});
}

Edge vs Serverless Comparison​

AspectEdgeServerless (Node.js)
Cold start~0ms250ms-1s
LocationCDN edgeRegions
Max execution30s300s
MemoryLimitedUp to 3GB
APIsWeb StandardFull Node.js
Use caseSimple, fastComplex ops

Key Points​

  • Edge runs at CDN locations for minimal latency
  • Near-zero cold starts
  • Use Web Standard APIs (fetch, Response, etc.)
  • No Node.js-specific APIs (fs, etc.)
  • Perfect for auth, A/B tests, redirects
  • Use Node.js for database operations with native drivers
  • Middleware always runs on Edge