Instant Edge Personalization Without Origin Roundtrips

Modern global web applications must adapt dynamically to visitor geographic locations: displaying local currency, enforcing GDPR cookie consent in the European Union, and redirecting users to regional language subpaths (e.g. /de/ or /jp/). Performing geolocation lookups on origin application servers introduces hundreds of milliseconds of latency. In Next.js 15, executing lightweight edge middleware directly at CDN edge nodes resolves country headers in under 5 milliseconds with zero origin hits.

Authored by Saizul Amin for frontend systems engineers and edge architecture developers.

Implementation: Edge Middleware with Country Header Rewrites


// middleware.ts
import { NextRequest, NextResponse } from '\''next/server'\'';

export function middleware(request: NextRequest) {
  // Read country header injected by Cloudflare / Vercel Edge Network
  const country = request.headers.get('\''x-vercel-ip-country'\'') || 
                  request.headers.get('\''cf-ipcountry'\'') || '\''US'\'';

  const response = NextResponse.next();
  response.headers.set('\''x-user-country'\'', country);

  // If EU visitor, set header flag for strict GDPR consent banner
  const euCountries = ['\''DE'\'', '\''FR'\'', '\''IT'\'', '\''ES'\'', '\''NL'\'', '\''SE'\'', '\''PL'\''];
  if (euCountries.includes(country)) {
    response.headers.set('\''x-require-gdpr-consent'\'', '\''true'\'');
  }

  return response;
}

export const config = {
  matcher: ['\''/((?!api|_next/static|_next/image|favicon.ico).*)'\''],
};

NEW BLOGS. REAL STRATEGIES. REAL RESULTS.

Join our community and receive powerful SEO tips, web optimization guides, and growth strategies as soon as they’re published.

Don’t just read blogs — stay ahead of the competition.

We don’t spam! Read our privacy policy for more info.

Share.
Leave A Reply