DEV Community

Build a Country Allowlist in Cloudflare Workers and Nginx

Product said the app should only be available in the United States and Canada. The first instinct was to drop a country database onto every origin and start returning 403s.

Then we remembered the Worker already has a country code on the request, for free, with no extra lookup.

A country gate is a coarse filter: it looks at the IP's country, not at the person. Behind a known VPN network, a Tor exit or a privacy relay, the country you see is the egress, not the user's. location.country_code can also be null, so every example below fails open when the country is unknown or the lookup errors. Use the ISO 3166-1 alpha-2 code (US, CA, …), not the city. City-level data is a best-effort estimate; save it for soft decisions like defaults or language, not a hard 403.

This post starts with request.cf.country, then shows when to look the IP up so Nginx can enforce the same rule. The longer version is the guide to blocking countries by IP in Workers and Nginx.

Start with request.cf.country

For the current visitor, Workers already give you a country code on request.cf.country. If all you need is "allow the United States and Canada, otherwise 403", use it. That is the right default, and it does not spend API quota.

// src/index.js - visitor country from request.cf (no API call)
const ALLOW = new Set(["US", "CA"]);
export default {
  async fetch(request) {
    const country = request.cf?.country; // ISO 3166-1 alpha-2, or undefined
    // Fail open when the country is missing.
    if (country && !ALLOW.has(country)) {
      return new Response("This service isn’t available in your country.", {
        status: 403,
      });
    }
    return fetch(request);
  },
};

Reach for GET /v0/ip/{ip} when Nginx at the origin has to enforce the same policy (there is no request.cf there), when you want one source of truth for Workers and origin, or when you're classifying IPs that are not the current visitor (logs, webhooks).

Country is part of geolocation, which is on the Free plan: 1,000 requests per UTC calendar month, 1 request/second, for personal and non-commercial use. Cache per IP or you'll burn the quota on repeat visitors. Commercial use needs a paid plan; paid plans start at $9/month. The country code, name, continent and is_eu fields are documented on the IP to Country API page.

When the Worker should look the IP up

Store the key with npx wrangler secret put NDL_API_KEY, not in wrangler.toml. The visitor IP is in CF-Connecting-IP. Cache the JSON per IP in the Cache API, keep a tight timeout and fall back to request.cf.country (or allow) if the call fails:

$ npx wrangler secret put NDL_API_KEY
// src/index.js
const API = "https://api.networkdatalabs.com/v0/ip/";
const TTL = 6 * 60 * 60; // seconds
const ALLOW = new Set(["US", "CA"]);

async function lookup(ip, env, ctx) {
  const cache = caches.default;
  const cacheKey = new Request(`https://ndl-cache.internal/ip/${ip}`);
  const hit = await cache.match(cacheKey);
  if (hit) return hit.json();
  const res = await fetch(API + encodeURIComponent(ip), {
    headers: { Authorization: `Bearer ${env.NDL_API_KEY}` },
    signal: AbortSignal.timeout(500),
  });
  if (!res.ok) throw new Error(`lookup ${res.status}`);
  const data = await res.json();
  ctx.waitUntil(
    cache.put(
      cacheKey,
      new Response(JSON.stringify(data), {
        headers: {
          "Cache-Control": `max-age=${TTL}`,
          "Content-Type": "application/json",
        },
      })
    )
  );
  return data;
}

function decide(country) {
  // No country β†’ fail open. Only block a known country outside the allowlist.
  if (!country) return true;
  return ALLOW.has(country);
}

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    if (url.pathname === "/health" || url.pathname.startsWith("/assets/")) {
      return fetch(request);
    }
    let country = request.cf?.country ?? null;
    const ip = request.headers.get("CF-Connecting-IP");
    try {
      if (ip) {
        const data = await lookup(ip, env, ctx);
        country = data.location?.country_code ?? country;
      }
    } catch {
      // fail open: keep request.cf, or allow if both are missing
    }
    if (!decide(country)) {
      return new Response("This service isn’t available in your country.", {
        status: 403,
      });
    }
    return fetch(request);
  },
};

The Cache API is per data center and costs nothing extra. If you want one shared cache across locations, store the JSON in Workers KV with expirationTtl instead.

Use request.cf.country when you only need the current visitor's country at the edge; use the API when origin must apply the same rule, or when you're looking up IPs that aren't this request. The two can occasionally disagree, so pick one source for the gate and stick to it.

Nginx: auth_request and a small sidecar

Nginx doesn't have the visitor country on its own unless you add a geo module or a local database. A small sidecar keeps the policy in one place: Nginx asks it on each request via auth_request, and the sidecar looks up GET /v0/ip/{ip}, caches the result and returns 200 (allow) or 403 (deny).

The sidecar must fail open too: API errors return 200, and if the sidecar itself is down, Nginx maps 502/503/504 to 200. Pass a single client IP in X-Client-IP. If Nginx is at the edge, that's $remote_addr. If Cloudflare is the only proxy in front of Nginx, use $http_cf_connecting_ip. Don't parse raw X-Forwarded-For - the client can put any address there.

// sidecar.js - Node 18+, listen on 127.0.0.1:8091
const http = require("http");
const API = "https://api.networkdatalabs.com/v0/ip/";
const KEY = process.env.NDL_API_KEY;
const ALLOW = new Set((process.env.ALLOWED_COUNTRIES || "US,CA").split(","));
const cache = new Map();
const TTL_MS = 6 * 60 * 60 * 1000;

function normalize(ip) {
  return ip && ip.startsWith("::ffff:") ? ip.slice(7) : ip;
}

async function lookup(ip) {
  const hit = cache.get(ip);
  if (hit && hit.exp > Date.now()) return hit.data;
  const res = await fetch(API + encodeURIComponent(ip), {
    headers: { Authorization: `Bearer ${KEY}` },
    signal: AbortSignal.timeout(800),
  });
  if (!res.ok) throw new Error(`lookup ${res.status}`);
  const data = await res.json();
  cache.set(ip, { data, exp: Date.now() + TTL_MS });
  return data;
}

http
  .createServer(async (req, res) => {
    if (req.url !== "/check") {
      res.writeHead(404);
      res.end();
      return;
    }
    const ip = normalize(req.headers["x-client-ip"]);
    try {
      const data = await lookup(ip);
      const country = data.location?.country_code ?? "";
      const allow = !country || ALLOW.has(country); // fail open if unknown
      res.writeHead(allow ? 200 : 403, {
        "X-IP-Country": country,
        "Cache-Control": "no-store",
      });
    } catch {
      res.writeHead(200, { "X-IP-Country": "" }); // fail open
    }
    res.end();
  })
  .listen(8091, "127.0.0.1");
# Requires the auth_request module (included in most nginx packages).
# Sidecar listens on 127.0.0.1:8091 (see sidecar.js).
upstream geo_sidecar {
  server 127.0.0.1:8091;
  keepalive 8;
}

server {
  listen 80;
  server_name app.example.com;

  location = /_country_gate {
    internal;
    proxy_pass http://geo_sidecar/check;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
    proxy_set_header X-Client-IP $remote_addr;
    # If Cloudflare is the only proxy in front of Nginx, use this instead:
    # proxy_set_header X-Client-IP $http_cf_connecting_ip;
    proxy_connect_timeout 200ms;
    proxy_read_timeout 800ms;
    proxy_intercept_errors on;
    error_page 502 503 504 = 200 /_country_allow;
  }

  location = /_country_allow {
    internal;
    return 200;
  }

  location / {
    auth_request /_country_gate;
    auth_request_set $ip_country $upstream_http_x_ip_country;
    error_page 403 = @country_denied;
    proxy_set_header X-IP-Country $ip_country;
    proxy_pass http://127.0.0.1:3000;
  }

  location @country_denied {
    default_type text/plain;
    return 403 "This service isn't available in your country.\n";
  }
}

auth_request_set copies X-IP-Country from the sidecar onto $ip_country, so the origin still sees the country after an allow. Skip the gate on health checks and static assets if you can, so those paths never spend a lookup (the in-process cache already covers repeat IPs).

Test fixtures, caching and a VPN caveat

  • 8.8.8.8 - a public US DNS resolver. The API returns location.country_code: "US" (and is_anycast / is_hosting). On an allowlist of US,CA it must be allowed.
  • 203.0.113.10 - a documentation (TEST-NET) address. It comes back with traits.is_bogon and no country, so the examples above allow it. Use it to check fail-open, not as a stand-in for a real user.
  • 127.0.0.1 and ::1 are bogon addresses with no country, so the snippets allow them in local development. Point the sidecar at a public US IP such as 8.8.8.8 when you want to see an allow, and temporarily shrink the allowlist when you want to see a 403.

Cache per IP for a few hours in the sidecar and in the Worker. Keep timeouts tight (500-800 ms) and always fail open on errors. Country is on the Free plan, but 1,000 requests/month is not enough to look up every request without a cache. For log backfill, POST /v0/bulk (paid plans) accepts up to 100 IPs per request; each IP counts toward the monthly quota.

If the user is on a VPN, you get the egress country. is_vpn (known VPN networks), is_tor and is_relay (privacy relay) are paid-plan flags on the same response if you want to treat that traffic differently. They are not required for a basic country gate.

  • The Network Data Labs team
Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.