Edge Runtime
Edge functions, edge middleware, edge-compatible libraries, and limitations.
Overview
Edge Runtime runs code at CDN edge locations for minimal latency.
Key Concepts
- Edge Functions — Run at the edge, not Node.js
- Edge Middleware — Middleware at the edge
- Web APIs — Use standard Web APIs (Request, Response)
- Limitations — No Node.js APIs, limited packages
- Performance — Sub-millisecond cold starts
Code Examples
// Edge middleware
export const config = {
matcher: '/api/:path*',
runtime: 'edge'
};
export async function middleware(request) {
const response = await fetch(request);
response.headers.set('x-edge', 'true');
return response;
}
// Edge API route
// app/api/edge/route.js
export const runtime = 'edge';
export async function GET(request) {
const { searchParams } = new URL(request.url);
const query = searchParams.get('q');
// Use edge-compatible database
const results = await edgeDB.query('SELECT * FROM items WHERE name = $1', [query]);
return Response.json(results);
}
// Edge-compatible auth
import { jwtVerify } from 'jose';
export async function verifyEdgeToken(token) {
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
const { payload } = await jwtVerify(token, secret);
return payload;
}
Practice
Convert a middleware to Edge Runtime and handle edge-compatible JWT verification.