Edge Runtime on Vercel: When to Use It and When to Avoid It
Edge Runtime promises lower latency by running code closer to users. But it comes with real constraints. Here's a practical guide to making the right runtime choice.
"Just add export const runtime = 'edge' and your API routes will be faster." That's the pitch, anyway. The reality is more nuanced. Edge Runtime runs your code on Vercel's global network — closer to users, lower latency — but it comes with a restricted API surface that can bite you hard in production.
After migrating several routes to Edge and rolling some back, here's what I've learned about when it makes sense and when it doesn't.
What Edge Runtime Actually Is
Edge Runtime uses the Web API standard — the same APIs available in Service Workers and Cloudflare Workers. It's not Node.js. You don't have access to fs, net, child_process, or most of the Node.js standard library. You get fetch, crypto, TextEncoder, URL, and the Web Streams API.
The key benefit: your function runs in the data center closest to the user instead of a single region. For a user in Tokyo hitting a US-East server, that's the difference between 200ms and 30ms of network latency.
When to Use Edge Runtime
Authentication and session validation: Checking a JWT, validating a session token, or running middleware auth checks. These are pure computation with no external dependencies — perfect for Edge.
// middleware.ts — runs on Edge by default
import { NextResponse } from "next/server";
import { jwtVerify } from "jose";
export async function middleware(request: NextRequest) {
const token = request.cookies.get("session")?.value;
if (!token) {
return NextResponse.redirect(new URL("/login", request.url));
}
try {
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
await jwtVerify(token, secret);
return NextResponse.next();
} catch {
return NextResponse.redirect(new URL("/login", request.url));
}
}
A/B testing and feature flags: Reading a cookie, making a routing decision, and returning a response. No database needed.
Geolocation-based responses: Edge functions receive the user's geo data. Redirect to regional content, show localized pricing, or select the nearest API endpoint.
Simple API proxies: Forwarding requests to an upstream API with added headers, rate limiting, or response transformation.
When to Avoid Edge Runtime
Database queries: This is the big one. If your route queries PostgreSQL, MySQL, or any TCP-based database, Edge won't work — it doesn't support raw TCP connections. You can use HTTP-based database proxies (like Neon's serverless driver or PlanetScale's fetch API), but now you're adding a proxy hop that may negate the latency benefit.
// ❌ This will NOT work on Edge Runtime
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
export const runtime = "edge"; // Fails: Prisma uses TCP
export async function GET() {
const posts = await prisma.post.findMany();
return Response.json(posts);
}
// ✅ Use Node.js runtime for database routes
export const runtime = "nodejs";
export async function GET() {
const posts = await prisma.post.findMany();
return Response.json(posts);
}
File system operations: No fs module. If you're reading templates, config files, or processing uploads that touch disk, stick with Node.js.
Heavy computation: Edge functions have strict CPU time limits (typically 5–30 seconds). Image processing, PDF generation, or complex data transformations will time out.
npm packages with Node.js dependencies: Many popular packages import Node.js built-ins internally. Sharp, Prisma (standard), bcrypt, and most ORMs won't work on Edge.
The Hybrid Approach
The best architecture uses Edge for what it's good at and Node.js for everything else. In Next.js, this is straightforward — each route segment can declare its own runtime:
- Middleware: Edge (default, handles auth/routing)
- API routes with DB: Node.js
- API routes without DB: Edge for latency-sensitive ones
- Server Components: Node.js (need full DB access)
Takeaways
- Edge Runtime is not Node.js — it's Web APIs only
- Use it for auth, middleware, A/B tests, and simple proxies
- Avoid it for database queries, file operations, and heavy computation
- Test your dependencies — many npm packages silently require Node.js
- Default to Node.js and only move to Edge when latency measurements justify it
Admin
Cal.com
Open source scheduling — tự host booking system, thay thế Calendly. Free & privacy-first.
Vercel
Deploy Next.js app trong 30 giây. Free tier rộng rãi cho side projects.
Bình luận (0)
Đăng nhập để bình luận
Chưa có bình luận nào. Hãy là người đầu tiên!