Tarek.
← All posts

Edge Computing with Next.js Middleware: A Practical Guide

· 1 min read · Admin

What is Edge Computing?

Edge computing runs your logic closer to users. Instead of processing requests in a single data center, edge functions execute at CDN nodes worldwide — typically within 50ms of the user.

Next.js Middleware at the Edge

typescript
// middleware.tsimport { NextRequest, NextResponse } from "next/server";​export function middleware(request: NextRequest) {  const country = request.geo?.country || "US";  if (country === "DE") {    return NextResponse.rewrite(new URL("/de" + request.nextUrl.pathname, request.url));  }  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: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],};

Edge vs Node.js Runtime

  • Edge: lower latency, smaller API surface, runs at CDN

  • Node.js: full API access, better for complex logic

  • Use edge for: redirects, rewrites, auth checks, geo-routing

  • Use Node.js for: database queries, file processing, complex API logic

Performance Impact

Moving authentication and routing logic to the edge can reduce TTFB by 50-200ms for users far from your origin server.