Blog
Get a visitor's country from their IP address in JavaScript and Node.js
Find a visitor's country from their IP in JavaScript: read your CDN's country header, query a local database in Node.js, or call an IP API, and read the right address.
Updated 2026-11-25
To get a visitor's country from their IP address, look it up on the server: the browser cannot see its own public address, but your server receives it with every request. You have three ways to turn that address into a country code. Read a header your CDN already adds, query a local database with Node.js, or call an IP lookup API. All three depend on one thing people often get wrong: reading the right client address.
Why the browser cannot do it alone
JavaScript in a page has no API that returns the public IP address. What it does have are hints that look like location but are not:
| Browser value | What it really is |
|---|---|
navigator.language |
The language the person chose. Many people outside the US use en-US. |
Intl.DateTimeFormat().resolvedOptions().timeZone |
The device's time zone setting. Several countries share each zone. |
navigator.geolocation |
Coordinates, after a permission prompt. Many people say no. |
So the country lookup runs on your server, and the page receives the result. If you need it in client code, expose a small endpoint that returns the country and nothing else.
Read the right client address
Every method below starts from the client address. Behind a proxy, load balancer or CDN, the TCP connection comes from the proxy, and the visitor's address is in a header.
- Express:
app.set('trust proxy', 1)trusts one proxy hop, andreq.ipbecomes the client address taken fromX-Forwarded-For. Set the number to the hops you control. - Cloudflare: read
CF-Connecting-IP, which Cloudflare sets to the address that connected to it. - Never trust
X-Forwarded-Forblindly. Anyone can send that header. Only the entries appended by your own proxies are reliable, which is what thetrust proxysetting counts. - Local development gives
127.0.0.1or::1. No database has a country for them, so handle a missing country as a normal case.
Option 1: read your CDN's country header
If traffic already passes through a CDN, it has looked the address up for you.
| Platform | Where the country is | Notes |
|---|---|---|
| Cloudflare | CF-IPCountry header, request.cf.country in Workers |
XX when there is no data, T1 for Tor. The header needs IP geolocation turned on in the zone's Network settings. |
| Vercel | x-vercel-ip-country header |
The two-letter country code of the address that made the request. |
| Amazon CloudFront | CloudFront-Viewer-Country header |
Forwarded once you add it to an origin request policy. |
A Cloudflare Worker reads it in one line:
export default {
async fetch(request) {
const country = request.cf?.country ?? null
return Response.json({ country: country === 'XX' || country === 'T1' ? null : country })
},
}
In Node.js behind Vercel or Cloudflare, read the header from the request:
function countryFromHeaders(headers) {
const value = headers['x-vercel-ip-country'] ?? headers['cf-ipcountry'] ?? null
if (!value || value === 'XX' || value === 'T1') return null
return value.toUpperCase()
}
The header is free and fast. Its limits: you only get the country, you cannot see which network the visitor is on, and the header is only trustworthy when the request really came through the CDN. If your origin is reachable directly, anyone can send CF-IPCountry: US.
Option 2: a local database in Node.js
When you run your own servers, query a database file in the MaxMind DB format (.mmdb) with the maxmind package. The lookup runs in memory, in microseconds, with no network call.
npm install maxmind
DB-IP publishes a free IP to Country Lite database in this format, updated monthly, under the Creative Commons Attribution 4.0 license. The license requires attribution: on a web application, DB-IP asks for a link back to DB-IP.com on pages that use the results. Download the file for the current month:
curl -sS https://download.db-ip.com/free/dbip-country-lite-2026-11.mmdb.gz | gunzip > dbip-country-lite.mmdb
Then serve the country from a small endpoint:
import express from 'express'
import maxmind from 'maxmind'
const countries = await maxmind.open('./dbip-country-lite.mmdb')
function countryOf(ip) {
if (!ip || !maxmind.validate(ip)) return null
return countries.get(ip)?.country?.iso_code ?? null
}
const app = express()
app.set('trust proxy', 1)
app.get('/api/geo', (req, res) => {
res.set('Cache-Control', 'private, no-store')
res.json({ country: countryOf(req.ip) })
})
app.listen(3000)
We ran this with maxmind 5.1.0 and the November 2026 file. 8.8.8.8 returned US, 81.2.69.142 returned GB, and the IPv6 address 2a00:1450:4007:80c::200e returned GB. Private addresses such as 192.168.1.10 returned null, and so did a request from localhost. IPv4-mapped IPv6 addresses such as ::ffff:8.8.8.8, which Node reports on dual-stack sockets, resolve like the plain IPv4 address.
The Cache-Control: private, no-store line matters: without it, a shared cache could serve one visitor's country to the next.
What to plan for:
- Updates. Networks move between countries. Schedule a monthly download and reopen the reader, or the answers drift.
- Memory. The file is loaded into the process. The country file was about 8 MB uncompressed in November 2026.
- Only the country. For the network type or VPN flags you need other data, as detect VPN and proxy traffic in Node.js shows.
Option 3: an IP lookup API
An API keeps the data current for you and returns more than the country: region, city, the network that announces the address and whether the traffic comes through Tor, a VPN, a proxy or a data center. Call it from your server with the client address.
const cache = new Map()
export async function lookupCountry(ip) {
if (cache.has(ip)) return cache.get(ip)
let result = null
try {
const response = await fetch('https://api.qelka.com/v1/ip', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.QELKA_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ ip }),
signal: AbortSignal.timeout(3000),
})
if (response.ok) result = await response.json()
} catch {
return null
}
const country = result?.country?.code ?? null
if (cache.size > 10000) cache.clear()
cache.set(ip, country)
return country
}
The response for 8.8.8.8:
{
"id": "lkp_01M86D8K5X579S8H6PX1RSA6T6",
"object": "ip",
"input": "8.8.8.8",
"version": 4,
"country": { "code": "US", "name": "United States" },
"region": "California",
"city": "Mountain View",
"asn": { "number": 15169, "org": "Google LLC", "type": "hosting" },
"flags": { "tor": false, "vpn": false, "proxy": false, "datacenter": true },
"risk": { "score": 35, "level": "medium" },
"credits_used": 1,
"cached": false
}
Each lookup costs 1 credit, cached or not. Private, loopback and documentation addresses return 422 unprocessable_input and are not billed, so the function above returns null for them, like the database did. The in-memory cache saves a credit when the same visitor loads several pages; in production, keep it per session or in your own store. The location data comes from DB-IP's Lite databases, credited on the data sources page, and the IP API reference lists every field.
With the official client the call is one line:
import { Client } from '@qelka/sdk'
const client = new Client({ apiKey: process.env.QELKA_API_KEY })
const ip = await client.ip.lookup({ ip: '8.8.8.8' })
console.log(ip.country?.code, ip.flags.vpn, ip.risk.level)
Which option to choose
| Need | Best fit |
|---|---|
| Country only, site behind a CDN | The CDN header |
| Country only, your own servers, high traffic | A local .mmdb file |
| Country plus network, VPN or Tor signals | The API |
| Country inside a signup or checkout decision | The API, with the result stored next to the order |
Use the country with care
- Make it a default, not a lock. Prefill the country selector, the currency or the phone prefix, and let the person change it. Travelers and VPN users would otherwise be stuck.
- Do not cache it in a shared page. A CDN cache keyed only on the URL serves one country to everyone.
- Compare it with other signals. A billing address in one country, a card from a second and an IP in a third is worth a look at checkout. IP geolocation accuracy explains when the country is wrong and why the city is approximate.
- Treat a missing country as normal. Localhost, new ranges and some mobile networks return none.
Try it
Look up any address with the free IP lookup, see what your own connection reveals with what is my IP, or check the network behind an address with the ASN lookup. The IP lookup API page covers pricing, and the Node.js, Express, Next.js and Cloudflare Workers pages show complete setups.
Frequently asked questions
Can JavaScript in the browser get the visitor's IP address or country?
navigator.language and the time zone from Intl are settings, not a location. The reliable route is to look the country up on your server, where the request arrives with the client address, and send it to the page.What is the easiest way to get the country of a request in Node.js?
CF-IPCountry on Cloudflare, x-vercel-ip-country on Vercel, CloudFront-Viewer-Country on CloudFront once it is enabled. It costs nothing and needs no database. Without a CDN, open a local IP database with the maxmind package, or call an IP lookup API from your server.How accurate is IP to country?
Can I use IP country for legal compliance such as geo-blocking?
Keep going
- Free toolIP lookupFind the country, region, city, network (ASN) and organization behind an IPv4 or IPv6 address, and whether it belongs to a data center or Tor.Try it
- APIIP geolocationCountry, region, city, ASN and organization for any public IPv4 or IPv6 address.See the API
- ArticleIP geolocation accuracy: what an IP address can and cannot tell youHow IP geolocation works, why the country is dependable and the city is approximate, what moves a location, and how to use it without misleading yourself.Read
- ArticleDetect VPN and proxy traffic in Node.js: Tor lists, hosting networks and an API checkDetect VPN, proxy, Tor and data center traffic in Node.js: build local signals from the Tor exit list and ASN data, add an API check, and turn them into friction.Read
Put this check in your product
Get an API key in under a minute. 100 free credits every month, no card required.
- 100 free credits a month
- No card
- Test keys spend nothing
- Cancel any time