Edge Functions and Middleware
Run code at the edge for auth, A/B testing, and geo-routing with minimal latency.
EdgeAdvanced
Why
Edge functions run in 300+ locations, reducing latency to <50ms for auth and routing logic. Cloudflare's edge network spans 330+ cities with sub-50ms p95 latency globally.
Edge functions reduce TTFB by 60-80% compared to origin servers, and Akamai reports 40% of enterprises now use edge compute in 2024.
When
Auth checks, geo-routing, A/B testing, or request rewriting at the edge. Avoid edge functions for stateful logic requiring database writes — edge runtimes have no persistent connection pool.
Skip if you need long-running tasks (>30s) or heavy CPU computation.
How
# Next.js middleware (runs at edge)
import { NextResponse } from 'next/server';
import { NextRequest } from 'next/server';
export function middleware(req: NextRequest) {
// Geo-based routing
const country = req.geo.country || 'US';
if (country === 'CN') {
return NextResponse.rewrite(new URL('/cn' + req.nextUrl.pathname, req.url));
}
// Auth check
const token = req.cookies.get('token');
if (!token && req.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', req.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon).*)'],
};
4. Verify deployment — curl -I https://your-app.example.com
5. Monitor logs — check for errors in first 5 minutes
6. Rollback if needed — revert to previous version
Example
# Vercel Edge Function
export default function handler(req: Request) {
const country = req.headers.get('x-vercel-ip-country');
return Response.json({
message: `Hello from ${country}`,
timestamp: Date.now(),
});
}
export const config = { runtime: 'edge' };
Common Problems
- ⚠No Node.js APIs — use Web APIs only (fetch, Response, Request)
- ⚠Cold start on first request — use edge config for warm state
- ⚠Configuration drift between environments — use infrastructure-as-code (Terraform/Pulumi) to keep dev/staging/prod identical
Best Practices
- ✓Keep middleware minimal — it runs on every request
- ✓Use edge config for feature flags — update without redeploy
- ✓Set up health checks and graceful shutdown — handle SIGTERM to drain in-flight requests before exit