Edge & Serverless Functions
Vercel provides two runtimes for server-side code: Edge Functions and Serverless Functions. Each has distinct performance characteristics and use cases.
Runtime Comparison
| Feature | Edge Functions | Serverless Functions |
|---|---|---|
| Cold start | ~0ms | 250ms+ |
| Execution limit | 30 seconds (streaming) | 60 seconds (Hobby) / 900s (Pro) |
| Max size | 4 MB | 250 MB |
| Runtime | V8 isolates | Node.js |
| Regions | All edge locations | Select regions |
| Node.js APIs | Subset only | Full access |
| NPM packages | Limited | Full support |
When to Use Each
Use Edge Functions When:
- You need the lowest possible latency globally
- The logic is lightweight (auth checks, redirects, A/B tests)
- You are transforming or personalizing responses
- You do not need Node.js-specific APIs like
fsor native modules
Use Serverless Functions When:
- You need full Node.js compatibility
- Your function depends on large NPM packages
- You are doing database queries with Node.js drivers
- The function performs heavy computation
Edge Middleware
Middleware runs before every request and is always deployed to the edge:
// middleware.ts (root of project)
import { NextRequest, NextResponse } from "next/server";
export function middleware(request: NextRequest) {
const token = request.cookies.get("session");
if (!token && request.nextUrl.pathname.startsWith("/dashboard")) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*", "/api/protected/:path*"],
};
Configuring the Runtime
Set the runtime for a Route Handler or page:
// app/api/fast/route.ts
export const runtime = "edge";
export async function GET() {
return new Response(JSON.stringify({ time: Date.now() }), {
headers: { "content-type": "application/json" },
});
}
// app/api/heavy/route.ts
export const runtime = "nodejs"; // default
export async function GET() {
// Full Node.js available here
return Response.json({ status: "ok" });
}
Performance Considerations
- Edge functions execute in the region closest to the user, reducing round-trip time
- Serverless functions execute in a single region by default; configure
preferredRegionto optimize placement near your database
// Run this serverless function near the US East database
export const preferredRegion = "iad1";
Region Selection Tips
| Database Location | Recommended Region |
|---|---|
| AWS us-east-1 | iad1 (Washington, D.C.) |
| AWS eu-west-1 | dub1 (Dublin) |
| AWS ap-northeast-1 | hnd1 (Tokyo) |
Start with the default Node.js runtime. Switch to Edge only when you have a clear latency requirement that benefits from running at the edge.