Edge Runtime in Next.js: When to Use It and When to Avoid It
Edge Runtime runs your code at CDN nodes worldwide, eliminating cold starts. Learn when it's the right choice and what limitations to expect.
What Is the Edge Runtime?
The Edge Runtime executes JavaScript at the network edge — CDN nodes geographically close to your users. Instead of routing requests to a single origin server in one region, edge functions run in 100+ locations worldwide. This means sub-10ms routing times for simple operations like A/B testing, authentication, and redirects.
In Next.js, you can opt into the Edge Runtime per route by exporting a config object.
Enabling Edge Runtime
// app/api/geo-redirect/route.ts
export const runtime = 'edge';
export async function GET(request: Request) {
const country = request.headers.get('x-vercel-ip-country') ?? 'US';
const redirects: Record<string, string> = {
DE: 'https://de.yoursite.com',
FR: 'https://fr.yoursite.com',
JP: 'https://jp.yoursite.com',
};
const target = redirects[country] ?? 'https://yoursite.com';
return Response.redirect(target, 302);
}
// middleware.ts — always runs on Edge Runtime
import { NextRequest, NextResponse } from 'next/server';
import { verifyJWT } from './lib/jwt-edge'; // must be edge-compatible
export async function middleware(req: NextRequest) {
const token = req.cookies.get('auth-token')?.value;
if (!token) {
return NextResponse.redirect(new URL('/login', req.url));
}
const valid = await verifyJWT(token);
if (!valid) {
return NextResponse.redirect(new URL('/login', req.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard/:path*', '/api/protected/:path*'],
};
What the Edge Runtime Supports
The Edge Runtime uses a restricted V8 environment — not full Node.js. What works:
- Web APIs:
fetch,Request,Response,URL,Headers - Web Crypto:
crypto.subtle,crypto.randomUUID() - Streams API, TextEncoder/Decoder
- Most pure JavaScript libraries
What does NOT work:
- Node.js built-ins:
fs,path,os,buffer(in most cases) - Native Node addons
- Most ORM clients (Prisma requires the Data Proxy or Neon's serverless driver)
Database at the Edge
Traditional database connections don't work at edge because TCP handshakes are expensive across distributed nodes. Use HTTP-based drivers:
// With Neon serverless (HTTP-based Postgres)
import { neon } from '@neondatabase/serverless';
export const runtime = 'edge';
export async function GET() {
const sql = neon(process.env.DATABASE_URL!);
const posts = await sql;
return Response.json(posts);
}
When to Use Edge Runtime
Use Edge Runtime for:
- Authentication middleware and JWT verification
- Geolocation-based routing or personalization
- A/B testing (decide which variant before HTML is served)
- Rate limiting at the edge
- Simple API routes with HTTP-based data sources
Stick with Node.js runtime for:
- Any code using Node.js built-ins
- Traditional database connections (Prisma with PgBouncer, etc.)
- File system operations
- Complex server-side rendering with many dependencies
Performance Reality Check
Edge Runtime eliminates cold starts (from 200-2000ms to <5ms) and reduces network latency. But for database-heavy routes, the database round-trip still dominates. The real win is for stateless operations and globally-distributed APIs.
Admin
Vercel
Deploy Next.js app trong 30 giây. Free tier rộng rãi cho side projects.
Cal.com
Open source scheduling — tự host booking system, thay thế Calendly. Free & privacy-first.
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!