Block or Redirect Visitors by Country in Node.js
Check the country on your server, with one cached IP lookup, and decide what each visitor gets.
To block or redirect by country, look up the visitor's IP address on your server, cache the answer, and apply your rules before you send the page. The script below does that with no packages. If a lookup fails, it lets the visitor through, and you can change that.
Node.js 18 or later, with no packages. Also in PHP.
1Read the visitor's address, and trust only your own proxy.
If visitors connect straight to Node.js, the connection's address is theirs. Behind your own proxy or load balancer, the connection comes from the proxy, which usually passes the visitor's address in X-Forwarded-For. Anyone can send that header, so set TRUSTED_PROXIES to the number of proxies you control and count from the right. If a visitor can reach your app without going through the proxy, they can fake it. On a hosting platform or CDN, check its documentation for the header it sets.
// How many reverse proxies of YOUR OWN append to X-Forwarded-For before a
// request reaches this app. 0 means visitors connect straight to Node.
const TRUSTED_PROXIES = Number(process.env.TRUSTED_PROXIES || 0);
// Private and local addresses have no country, so don't spend a lookup on them.
const notPublic = new net.BlockList();
for (const [address, bits] of [['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10],
['127.0.0.0', 8], ['169.254.0.0', 16], ['172.16.0.0', 12], ['192.168.0.0', 16]]) {
notPublic.addSubnet(address, bits, 'ipv4');
}
notPublic.addAddress('::1', 'ipv6');
notPublic.addSubnet('fc00::', 7, 'ipv6');
notPublic.addSubnet('fe80::', 10, 'ipv6');
function clientIp(req) {
let ip = req.socket.remoteAddress || '';
if (TRUSTED_PROXIES > 0) {
// Count from the right: anything further left can be typed in by the visitor.
const chain = String(req.headers['x-forwarded-for'] || '').split(',');
ip = (chain[chain.length - TRUSTED_PROXIES] || '').trim() || ip;
}
// Some load balancers add a port: 203.0.113.7:5555 or [2001:db8::1]:5555.
ip = ip.replace(/^\[(.*)\](:\d+)?$/, '$1').replace(/^([\d.]+):\d+$/, '$1');
ip = ip.split('%')[0].replace(/^::ffff:(?=\d+\.)/i, ''); // zone ID, IPv4-mapped
const family = net.isIP(ip);
if (!family || notPublic.check(ip, family === 6 ? 'ipv6' : 'ipv4')) return null;
return ip;
}2Look up the country with one HTTPS request.
Create a free key (2,000 lookups a day, no card) and keep it on your server, in an environment variable. get=geoLocation asks for the location block only. Here is a request and an example reply:
curl -H "Authorization: Bearer $IPWHO_API_KEY" \
"https://api.ipwho.org/ip/91.0.0.1?get=geoLocation"{
"success": true,
"data": {
"geoLocation": {
"accuracy_radius": 5,
"capital": "Berlin",
"city": "Düsseldorf",
"continent": "Europe",
"continentCode": "EU",
"country": "Germany",
"countryCode": "DE",
"dial_code": "+49",
"is_in_eu": true,
"latitude": 51.2294,
"longitude": 6.7855,
"postal_Code": "40211",
"region": "North Rhine-Westphalia",
"regionCode": "NW"
}
}
}
Your rules need only data.geoLocation.countryCode. It can be null. A private or reserved address gets HTTP 404. The code gives the request 1.5 seconds, so a slow lookup can't hang a page for longer than that.
async function lookupCountry(ip) {
const res = await fetch(`https://api.ipwho.org/ip/${ip}?get=geoLocation`, {
headers: { Authorization: `Bearer ${API_KEY}`, 'User-Agent': 'country-gate/1.0' },
signal: AbortSignal.timeout(1500),
});
if (res.status === 404) return null; // reserved or unrecognised address
if (res.status === 429) pausedUntil = Date.now() + MINUTE;
if (!res.ok) throw new Error(`IPWho returned HTTP ${res.status}`);
const body = await res.json();
if (!body.success) throw new Error(body.message || 'IPWho lookup failed');
return body.data?.geoLocation?.countryCode ?? null;
}3Cache each answer, so repeat requests don't use lookups.
One page view can mean many requests. The cache keeps a successful answer for 24 hours and a failed one for a minute. It also shares a lookup that is still in progress, and stops calling for a minute after an HTTP 429 (a rate or daily limit). Our API terms let you cache results inside your own application for a reasonable time, as long as you don't resell or expose them.
This cache lives in one process's memory, so a restart empties it and each extra process keeps its own. If you run several, use a shared store such as Redis. Bots have IP addresses too, so count their traffic when you pick a plan.
const cache = new Map(); // ip -> { country: Promise, expires: number }
let pausedUntil = 0; // set after an HTTP 429, so we stop calling for a minute
// Resolves to a country code, or null when we don't know. It never rejects.
function countryFor(ip) {
const hit = cache.get(ip);
if (hit && hit.expires > Date.now()) return hit.country;
if (pausedUntil > Date.now()) return Promise.resolve(null);
// Cache the promise, so ten requests arriving together make one lookup.
const entry = { expires: Date.now() + DAY };
entry.country = lookupCountry(ip).catch((error) => {
entry.expires = Date.now() + MINUTE; // try this address again soon
console.warn('country lookup failed:', error.message);
return null;
});
cache.delete(ip);
cache.set(ip, entry);
if (cache.size > MAX_CACHED) cache.delete(cache.keys().next().value);
return entry.country;
}4Block, redirect or let through, and decide what “unknown” means.
A blocked visitor gets HTTP 403. If you block for a legal reason, HTTP 451 says so. A redirect uses 302, because browsers can remember a 301. Only the home page redirects, so deep links still work, and a link to /?stay=1 lets a visitor stay.
If there's no country, because a lookup failed or the reply has none, this code lets the visitor through (“fails open”). For a strict rule you can block unknown visitors instead, but then a failed lookup blocks a real visitor.
// Your rules, as two-letter country codes. Replace the examples.
const BLOCKED = new Set((process.env.BLOCKED_COUNTRIES || 'AQ')
.split(',').map((code) => code.trim().toUpperCase()));
const HOME_REDIRECTS = new Map([['DE', '/de/'], ['FR', '/fr/']]);
function decide(country, path, stay) {
if (!country) return { action: 'allow' }; // unknown: fail open
if (BLOCKED.has(country)) return { action: 'block' };
// Redirect the home page only, and respect a visitor who chose to stay.
if (path === '/' && !stay && HOME_REDIRECTS.has(country)) {
return { action: 'redirect', to: HOME_REDIRECTS.get(country) };
}
return { action: 'allow' };
}
const server = http.createServer(async (req, res) => {
const [path, query = ''] = req.url.split('?');
const choseToStay = new URLSearchParams(query).has('stay');
const stay = choseToStay || /(^|;\s*)region_choice=stay/.test(req.headers.cookie || '');
const ip = clientIp(req);
const country = ip ? await countryFor(ip) : null;
const result = decide(country, path, stay);
// The answer depends on who is asking, so a shared cache must not reuse it.
res.setHeader('Cache-Control', 'private, no-store');
if (choseToStay) {
res.setHeader('Set-Cookie', 'region_choice=stay; Path=/; Max-Age=31536000; SameSite=Lax');
}
if (result.action === 'block') {
res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
return res.end('Sorry, this site is not available in your country.\n');
}
if (result.action === 'redirect') {
res.writeHead(302, { Location: result.to }); // temporary, never 301
return res.end();
}
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(`Hello. Country: ${country || 'unknown'}. Path: ${path}\n`);
});5Run the full script and test all three outcomes.
Save this as country-gate.mjs. Replace the example rules and the “Hello” response with your own.
// country-gate.mjs: block or redirect visitors by country with the IPWho API.
// Node.js 18 or later, no packages. Run: IPWHO_API_KEY=sk.xxx node country-gate.mjs
import http from 'node:http';
import net from 'node:net';
const API_KEY = process.env.IPWHO_API_KEY;
if (!API_KEY) throw new Error('Set IPWHO_API_KEY first');
// Your rules, as two-letter country codes. Replace the examples.
const BLOCKED = new Set((process.env.BLOCKED_COUNTRIES || 'AQ')
.split(',').map((code) => code.trim().toUpperCase()));
const HOME_REDIRECTS = new Map([['DE', '/de/'], ['FR', '/fr/']]);
// How many reverse proxies of YOUR OWN append to X-Forwarded-For before a
// request reaches this app. 0 means visitors connect straight to Node.
const TRUSTED_PROXIES = Number(process.env.TRUSTED_PROXIES || 0);
const PORT = Number(process.env.PORT || 3000);
const DAY = 24 * 60 * 60 * 1000;
const MINUTE = 60 * 1000;
const MAX_CACHED = 50_000;
// Private and local addresses have no country, so don't spend a lookup on them.
const notPublic = new net.BlockList();
for (const [address, bits] of [['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10],
['127.0.0.0', 8], ['169.254.0.0', 16], ['172.16.0.0', 12], ['192.168.0.0', 16]]) {
notPublic.addSubnet(address, bits, 'ipv4');
}
notPublic.addAddress('::1', 'ipv6');
notPublic.addSubnet('fc00::', 7, 'ipv6');
notPublic.addSubnet('fe80::', 10, 'ipv6');
function clientIp(req) {
let ip = req.socket.remoteAddress || '';
if (TRUSTED_PROXIES > 0) {
// Count from the right: anything further left can be typed in by the visitor.
const chain = String(req.headers['x-forwarded-for'] || '').split(',');
ip = (chain[chain.length - TRUSTED_PROXIES] || '').trim() || ip;
}
// Some load balancers add a port: 203.0.113.7:5555 or [2001:db8::1]:5555.
ip = ip.replace(/^\[(.*)\](:\d+)?$/, '$1').replace(/^([\d.]+):\d+$/, '$1');
ip = ip.split('%')[0].replace(/^::ffff:(?=\d+\.)/i, ''); // zone ID, IPv4-mapped
const family = net.isIP(ip);
if (!family || notPublic.check(ip, family === 6 ? 'ipv6' : 'ipv4')) return null;
return ip;
}
const cache = new Map(); // ip -> { country: Promise, expires: number }
let pausedUntil = 0; // set after an HTTP 429, so we stop calling for a minute
async function lookupCountry(ip) {
const res = await fetch(`https://api.ipwho.org/ip/${ip}?get=geoLocation`, {
headers: { Authorization: `Bearer ${API_KEY}`, 'User-Agent': 'country-gate/1.0' },
signal: AbortSignal.timeout(1500),
});
if (res.status === 404) return null; // reserved or unrecognised address
if (res.status === 429) pausedUntil = Date.now() + MINUTE;
if (!res.ok) throw new Error(`IPWho returned HTTP ${res.status}`);
const body = await res.json();
if (!body.success) throw new Error(body.message || 'IPWho lookup failed');
return body.data?.geoLocation?.countryCode ?? null;
}
// Resolves to a country code, or null when we don't know. It never rejects.
function countryFor(ip) {
const hit = cache.get(ip);
if (hit && hit.expires > Date.now()) return hit.country;
if (pausedUntil > Date.now()) return Promise.resolve(null);
// Cache the promise, so ten requests arriving together make one lookup.
const entry = { expires: Date.now() + DAY };
entry.country = lookupCountry(ip).catch((error) => {
entry.expires = Date.now() + MINUTE; // try this address again soon
console.warn('country lookup failed:', error.message);
return null;
});
cache.delete(ip);
cache.set(ip, entry);
if (cache.size > MAX_CACHED) cache.delete(cache.keys().next().value);
return entry.country;
}
function decide(country, path, stay) {
if (!country) return { action: 'allow' }; // unknown: fail open
if (BLOCKED.has(country)) return { action: 'block' };
// Redirect the home page only, and respect a visitor who chose to stay.
if (path === '/' && !stay && HOME_REDIRECTS.has(country)) {
return { action: 'redirect', to: HOME_REDIRECTS.get(country) };
}
return { action: 'allow' };
}
const server = http.createServer(async (req, res) => {
const [path, query = ''] = req.url.split('?');
const choseToStay = new URLSearchParams(query).has('stay');
const stay = choseToStay || /(^|;\s*)region_choice=stay/.test(req.headers.cookie || '');
const ip = clientIp(req);
const country = ip ? await countryFor(ip) : null;
const result = decide(country, path, stay);
// The answer depends on who is asking, so a shared cache must not reuse it.
res.setHeader('Cache-Control', 'private, no-store');
if (choseToStay) {
res.setHeader('Set-Cookie', 'region_choice=stay; Path=/; Max-Age=31536000; SameSite=Lax');
}
if (result.action === 'block') {
res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
return res.end('Sorry, this site is not available in your country.\n');
}
if (result.action === 'redirect') {
res.writeHead(302, { Location: result.to }); // temporary, never 301
return res.end();
}
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(`Hello. Country: ${country || 'unknown'}. Path: ${path}\n`);
});
server.listen(PORT, () => console.log(`Listening on port ${PORT}`));
# Terminal 1. TRUSTED_PROXIES=1 and BLOCKED_COUNTRIES=JP are for this test.
IPWHO_API_KEY=sk.xxx TRUSTED_PROXIES=1 BLOCKED_COUNTRIES=JP node country-gate.mjs# Terminal 2. The header stands in for your proxy.
$ curl -s -w '[%{http_code}] %{redirect_url}\n' -H 'X-Forwarded-For: 8.8.8.8' http://localhost:3000/
Hello. Country: US. Path: /
[200]
$ curl -s -w '[%{http_code}] %{redirect_url}\n' -H 'X-Forwarded-For: 91.0.0.1' http://localhost:3000/
[302] http://localhost:3000/de/
$ curl -s -w '[%{http_code}] %{redirect_url}\n' -H 'X-Forwarded-For: 133.0.0.1' http://localhost:3000/
Sorry, this site is not available in your country.
[403]
In production, set TRUSTED_PROXIES to match your real setup, and leave it at 0 if you have no proxy.
Check these before you switch it on.
- Search engines. Google says its crawler usually comes from the US and advises against automatically redirecting people between language versions of a site, because people and search engines may then miss some versions. A banner with a link is often the safer choice. If you block the US, Google says to block its crawler too when it comes from the US, so Google may be unable to crawl your site. Don't make an exception for it.
- Rate limiting. Put a rate limit in front of this code, so one source can't use up your daily lookups.
- VPNs and proxies. A visitor using one can appear to be in another country.
- Legal rules. If a law requires you to block a country, get advice on what else it expects.
- Caches and CDNs. If a CDN or page cache answers without running your code, your rules don't run. Keep it from caching the pages you guard. The script marks its responses
private, no-store. - Privacy. IP addresses can be personal data. Say in your privacy notice that you send them to a lookup service. This script doesn't write them to its log.
Start with a free API key
Free tier: 2,000 lookups a day, no card. Paid plans from $2.50 a month billed yearly. See the full field reference.