← Back to Docs
Recipe

Recipe: Geo-aware request routing

Route users to the nearest edge node based on their geographic location. Reduce latency and keep data within regional boundaries.

Ingredients

  • Cloudflare Workers or Vercel Edge Middleware
  • Request.cf country / region / city fields
  • GeoIP database (MaxMind or IP2Location) for fallback
  • Regional origin servers or edge-optimized CDN

Steps

  1. Extract geo hints. Read request.cf.country from the incoming request on the edge.
  2. Map region to origin. Maintain a lookup table: EU → Frankfurt, NA → Virginia, APAC → Singapore.
  3. Rewrite upstream. Forward the request to the closest healthy origin. Use weighted fallback if the primary is degraded.
  4. Set response headers. Stamp x-served-by and x-geo-region for observability.
  5. Cache regionally. Partition cache keys by region to avoid cross-region cache poisoning.

Gotchas

  • VPNs and Tor exit nodes skew geo data — treat unknown as a region.
  • GDPR may require EU traffic to stay in EU; encode this in routing rules.
  • Stale GeoIP databases misroute traffic; refresh weekly.