Middleware, Edge Runtime & API Layer 🌍
Next.js middleware lets you intercept requests at the edge, while route handlers build APIs without leaving the repo.
Middleware 🎚️
middleware.ts runs before requests hit routes.
Use cases:
- Rewrites/Redirects: rewrite
/blogto/news. - Auth checks: verify JWT/cookie; redirect to login.
- Locale detection: inspect
Accept-Language, rewrite to/enor/fr. - A/B testing: bucket users and rewrite to variant routes.
- Feature flags: attach headers or rewrite to gated content.
Example:
import { NextResponse } from 'next/server';
export function middleware(req: NextRequest) {
const token = req.cookies.get('session');
if (!token && req.nextUrl.pathname.startsWith('/app')) {
return NextResponse.redirect(new URL('/login', req.url));
}
return NextResponse.next();
}Edge vs Node Runtime ⚖️
| Aspect | Edge Runtime | Node Runtime |
|---|---|---|
| Location | CDN edge (V8 isolates) | Server/Serverless Node.js |
| Cold starts | Very low | Higher |
| APIs available | Web APIs (fetch, Request), no fs | Full Node APIs |
| Libraries | Must be edge-compatible (no native modules) | Most npm packages |
| Use cases | Auth checks, geo routing, low-latency APIs | Complex logic, heavy libs, DB drivers |
Choose Edge for latency-sensitive logic or simple transformations. Keep DB-heavy tasks in Node runtime.
Route Handlers (API) 🍳
- Live under
app/api/.../route.ts. - Return
NextResponseorResponse. - Support streaming, uploads, CORS.
export async function OPTIONS() {
return NextResponse.json({}, { status: 204, headers: { 'Access-Control-Allow-Origin': '*' } });
}CORS
Set headers or use NextResponse.next({ headers }). For complex cases, create a helper to attach Access-Control-Allow-*.
Uploads & Streaming
Use req.formData() for small files; for large, stream to storage or generate presigned URLs.
export async function POST(req: Request) {
const encoder = new TextEncoder();
const stream = new ReadableStream({
start(controller) {
controller.enqueue(encoder.encode('chunk1'));
controller.close();
},
});
return new Response(stream);
}Webhooks & Background Jobs
- Handle Stripe/GitHub webhooks in route handlers; verify signatures before processing.
- For long tasks, enqueue jobs to queues (BullMQ, Cloud Tasks) and respond quickly.
Analogy: Middleware is your border checkpoint, the Edge runtime is the fast lane near the user, and route handlers are the custom kiosks issuing data passports.
Last updated on