How to Block or Allow Countries by IP in Cloudflare Workers and Nginx

Build a country allowlist or blocklist at the edge and at the origin: request.cf.country in a Worker, or Nginx auth_request to a small cached sidecar.

Sign up Read the docs

Free: 1,000 req/month · HTTPS · personal & non-commercial use

When a country allow/block list makes sense

Licensing, product availability and some compliance rules are decided at the country level. 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; accuracy_radius_km and confidence tell you when not to trust it. A country allowlist does not need the city at all.

Cloudflare Workers: start with request.cf.country

For the current visitor, Workers already give you a country code on request.cf.country, free and with no extra lookup. 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.

request.cf allowlist
// 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 included on the Free plan (1,000 requests per UTC calendar month, 1 request/second, personal and non-commercial use). Cache per IP or you’ll burn the quota on repeat visitors. Commercial use requires a paid plan; paid tiers are Starter $9 / 100k / 10 req/s, Growth $29 / 500k / 25 req/s and Scale $79 / 2M / 50 req/s, with no overage charges.

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:

Terminal
$ npx wrangler secret put NDL_API_KEY
src/index.js
// 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. For a deeper look at traits (is_hosting, is_tor, known VPN networks) on top of country, see Cloudflare Workers: beyond request.cf.

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
// 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");
nginx.conf (excerpt)
# 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

  • 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.

Caching, timeouts and quota

  • 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.

FAQ

Should I use request.cf or the API in a Worker?

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

What 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. More in the VPN detection API.

Can I block on city or region?

Don’t, for a hard gate. Use country_code only. Reach for city or region when confidence is high or medium and the decision is soft (defaults, language), not a 403.

What happens in local development?

127.0.0.1 and ::1 are bogon addresses with no country, so the snippets allow them. 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.

Related

Sign up Read the docs