DEV Community

Olly
Olly

Posted on

Show the cookie banner only to EU visitors: an Express middleware using IP geolocation

Showing a consent banner to every visitor annoys people outside the EU, and hiding it from everyone is a compliance risk. A cheap middle path: look up the visitor's IP once, cache the answer, and show the banner only when the address is in an EU country.

The IP lookup endpoint returns an is_eu boolean, so there is no country list to maintain. Here is the real response for a German address (tested live):

{
  "asn": 60729,
  "continent_code": "EU",
  "country": "Germany",
  "country_code": "DE",
  "ip": "185.220.101.1",
  "is_eu": true,
  "is_global": true,
  "is_private": false,
  "organization": "Stiftung Erneuerbare Freiheit",
  "version": 4
}
Enter fullscreen mode Exit fullscreen mode

For 8.8.8.8 the same call gives "country_code": "US" and "is_eu": false. A malformed address returns HTTP 422 with {"error": "ip must be a valid IPv4 or IPv6 address"}.

The call

curl "https://geoip-ip-geolocation-asn-isp-lookup.p.rapidapi.com/lookup?ip=8.8.8.8" \
  -H "X-RapidAPI-Key: YOUR_RAPIDAPI_KEY" \
  -H "X-RapidAPI-Host: geoip-ip-geolocation-asn-isp-lookup.p.rapidapi.com"
Enter fullscreen mode Exit fullscreen mode

The middleware (Node 18+, Express)

const express = require("express");
const HOST = process.env.GEO_HOST || "geoip-ip-geolocation-asn-isp-lookup.p.rapidapi.com";
const BASE = process.env.GEO_BASE || `https://${HOST}`;
const HEADERS = { "X-RapidAPI-Key": process.env.RAPIDAPI_KEY || "", "X-RapidAPI-Host": HOST };
const cache = new Map(); // ip -> { isEu, exp }
const TTL = 24 * 3600 * 1000;

async function isEuIp(ip) {
  const hit = cache.get(ip);
  if (hit && hit.exp > Date.now()) return hit.isEu;
  const r = await fetch(`${BASE}/lookup?ip=${encodeURIComponent(ip)}`, { headers: HEADERS, signal: AbortSignal.timeout(1500) });
  if (!r.ok) throw new Error(`geo ${r.status}`);
  const j = await r.json();
  const isEu = j.is_global ? j.is_eu : false;
  cache.set(ip, { isEu, exp: Date.now() + TTL });
  return isEu;
}

function euConsent() {
  return async (req, res, next) => {
    const ip = (req.headers["x-forwarded-for"] || req.socket.remoteAddress || "").split(",")[0].trim().replace(/^::ffff:/, "");
    try { res.locals.showConsent = await isEuIp(ip); }
    catch (e) { res.locals.showConsent = true; } // fail safe: treat as EU
    next();
  };
}

const app = express();
app.set("trust proxy", true);
app.use(euConsent());
app.get("/", (req, res) => res.send(res.locals.showConsent ? "banner: shown" : "banner: hidden"));
module.exports = { app, isEuIp };
if (require.main === module) app.listen(3000);
Enter fullscreen mode Exit fullscreen mode

Design choices worth noting:

  • Fail safe. If the lookup times out (1.5 s) or errors, the middleware treats the visitor as EU and shows the banner. A wrongly shown banner is harmless; a wrongly hidden one is not.
  • Cache per IP for 24 hours, so a returning visitor costs no extra request. For a real site swap the Map for Redis or an LRU with a size cap.
  • Private and loopback addresses (is_global: false) are treated as not EU, so local development doesn't show the banner. Flip that if you prefer.
  • Behind a proxy you need trust proxy so req.headers["x-forwarded-for"] is the visitor, not your load balancer.
  • If you need to check many addresses at once (for example a log file), POST /bulk takes {"ips": [...]} with 1 to 100 addresses and returns {"results": [...]} in input order.

Limits

The free plan has a monthly request quota, and with a 24 h cache you only spend one request per unique visitor per day. Geolocation is approximate: a VPN user appears in the VPN's country, so treat this as a UX default, not legal advice. Consult your own counsel for what your site must do.

Doing it locally

You can download a geolocation database and query it in-process, which is free per request but means shipping a file of tens of MB, refreshing it monthly, and wiring up a reader library. The API is the better fit for a small site where you'd rather have one fetch call and no data files.

The free plan is enough to try it: GeoIP on RapidAPI

IP geolocation by DB-IP, CC BY 4.0.

Top comments (0)