IP geolocation in Node.js
Find the country, city and ISP of a visitor in Node.js 18+ with the built-in fetch, an Express middleware for the client address and an in-memory cache.
This guide shows IP geolocation in Node.js with nothing but the built-in fetch (Node.js 18 and newer). It covers a single lookup, a small module with a timeout and a cache, and an Express middleware that adds the visitor's country to every request.
Setup
Create an IPIDB account and copy the API key from the dashboard; the free plan gives 1,000 lookups a day. Pass the key through the environment:
export IPIDB_KEY=your_api_key node --version # v18 or newer
One lookup
const res = await fetch("https://api.ipidb.com/v1/ip/8.8.8.8", { headers: { "X-API-Key": process.env.IPIDB_KEY }, signal: AbortSignal.timeout(5000), }); const data = await res.json(); if (data.success) { const { city, country, latitude, longitude } = data.location; console.log(`${city}, ${country} (${latitude}, ${longitude})`); console.log(data.timezone.id, data.network.asn, data.network.isp); } else { console.error(res.status, data.error.code); }
Run it with node lookup.mjs. The file ends in .mjs so that top-level await works without a build step.
A module with a timeout and a cache
An HTTP call on every page view is wasteful: an address keeps its location for days. The module below keeps answers in a Map for an hour, limits the size of the cache and returns null instead of throwing, so a slow network never breaks a page.
const API = "https://api.ipidb.com/v1"; const TTL = 60 * 60 * 1000; const MAX = 50000; const cache = new Map(); export async function lookup(ip, fields) { const key = ip + "|" + (fields || ""); const hit = cache.get(key); if (hit && hit.until > Date.now()) return hit.data; const url = new URL(`${API}/ip/${encodeURIComponent(ip)}`); if (fields) url.searchParams.set("fields", fields); let data; try { const res = await fetch(url, { headers: { "X-API-Key": process.env.IPIDB_KEY }, signal: AbortSignal.timeout(4000), }); data = await res.json(); } catch (err) { console.warn("ipidb:", err.name); return null; } if (!data.success) { console.warn("ipidb:", data.error.code, ip); return null; } if (cache.size >= MAX) cache.delete(cache.keys().next().value); cache.set(key, { data, until: Date.now() + TTL }); return data; }
Express middleware
The middleware looks up the visitor and stores the country code on req.geo. Set trust proxy only when the app really runs behind your own proxy or load balancer; then Express reads the client address from X-Forwarded-For.
import express from "express"; import { lookup } from "./ipidb.mjs"; const app = express(); app.set("trust proxy", "loopback"); app.use(async (req, res, next) => { const geo = await lookup(req.ip, "location.country_code,location.is_eu,timezone.id"); req.geo = { country: geo?.location?.country_code ?? null, isEU: geo?.location?.is_eu ?? null, timezone: geo?.timezone?.id ?? null, }; next(); }); app.get("/", (req, res) => { res.json(req.geo); }); app.listen(3000);
Install Express with npm install express and start the server with node server.mjs. location.is_eu is handy for deciding whether to show a cookie consent banner.
Errors worth handling
rate_limited(429): more requests per second than the plan allows; the response carriesRetry-After: 1.quota_exceeded(429): the daily or monthly quota is used;X-Quota-Resetholds the reset time as a Unix timestamp.invalid_key(401): check the environment variable.
Local addresses such as 127.0.0.1 or 192.168.1.10 have no location; during development you will see empty location fields for them. Every code is listed in the error reference.
In the browser
Do not put a key into front-end code that anyone can read. If you must call the API from the browser, limit the key to your website's domain in the dashboard; requests from other origins then get 403 origin_not_allowed.
Related
- API documentation: every endpoint, field and error code
- IPIDB APIs: IP data, blacklist and MAC vendor lookups
- Pricing: the free plan and what paid plans add
- IP geolocation in PHP
- IP geolocation in Python
- IP geolocation in Go
- Block countries in nginx with an MMDB database
- Detect VPN and proxy logins