Prompt
How do I do geo-based routing with edge functions?
Latest observation
Oct 26, 2026
OpenAI APIWeb search: off
Geo-based routing with edge functions usually means:
- Detect the visitor’s location at the edge using request headers or edge runtime context.
- Choose a backend, page variant, or redirect target based on country/region/city.
- Return the response as early as possible from the edge so the user gets low-latency routing.
Common pattern
1) Read geo info from the request
Many edge runtimes expose geolocation via headers like:
CF-IPCountryon Cloudflarex-vercel-ip-countryon Vercelx-country/ platform-specific headers on others
Example logic:
- US → send to
/us - EU → send to
/eu - otherwise → default
2) Route or rewrite
You can:
- Redirect the user to a geo-specific URL
- Rewrite the request internally
- Proxy to a region-specific origin
- Serve localized content directly from the edge
Example: simple geo redirect
export default {
async fetch(request) {
const country = request.headers.get("cf-ipcountry") || "unknown";
if (country === "US") {
return Response.redirect("https://example.com/us", 302);
}
if (country === "DE" || country === "FR" || country === "NL") {
return Response.redirect("https://example.com/eu", 302);
}
return fetch(request);
}
}
Example: internal rewrite
If you want to keep the browser URL the same:
export default {
async fetch(request) {
const country = request.headers.get("cf-ipcountry") || "unknown";
const url = new URL(request.url);
if (country === "US") url.pathname = "/us" + url.pathname;
else if (["DE", "FR", "NL"].includes(country)) url.pathname = "/eu" + url.pathname;
return fetch(new Request(url, request));
}
}
Best practices
- Provide a fallback if geo data is missing or inaccurate.
- Avoid hard-blocking users purely by geo unless necessary.
- Cache carefully so one country’s content doesn’t leak to another.
- Use
Varyheaders or separate cache keys when content differs by geo. - Support manual overrides (e.g. a language selector or cookie) so users can choose their region.
Important caching note
If you serve different content by country, make sure caches separate it. Depending on platform, you may need to:
- include country in the cache key
- set
Vary: CF-IPCountryor equivalent - use edge cache segmentation by region
If you tell me your platform
If you let me know whether you’re using Cloudflare Workers, Vercel Edge Functions, Netlify, Fastly, AWS Lambda@Edge, or another platform, I can give you an exact implementation for that stack.