Skip to Content
Nextjs7.1 Middleware, Edge & API Layer

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 /blog to /news.
  • Auth checks: verify JWT/cookie; redirect to login.
  • Locale detection: inspect Accept-Language, rewrite to /en or /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 ⚖️

AspectEdge RuntimeNode Runtime
LocationCDN edge (V8 isolates)Server/Serverless Node.js
Cold startsVery lowHigher
APIs availableWeb APIs (fetch, Request), no fsFull Node APIs
LibrariesMust be edge-compatible (no native modules)Most npm packages
Use casesAuth checks, geo routing, low-latency APIsComplex 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 NextResponse or Response.
  • 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