How to Detect VPN Traffic in Node.js and Python

Add Express and FastAPI middleware that reads known VPN network, Tor exit, privacy relay and hosting flags, then logs, rate-limits or steps up — without hard-blocking real users.

Sign up Read the docs

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

What this guide covers (and what it doesn’t)

This is a recipe for live request traffic in Express and in Python (FastAPI / Starlette): middleware that looks up the client IP, reads the risk flags, and decides whether to log, rate-limit or step up verification. It is not a signup scoring policy — for that, use Flag risky signups in Python by IP.

A “VPN detection” flag is not a verdict that the person is hiding something, and it is not proxy detection. traits.is_vpn means the IP belongs to a known VPN network, including major commercial VPN providers. Whole networks of VPN-heavy hosting providers are flagged, so other servers on those networks are flagged too. A brand-new VPN range can still show false until the data picks it up.

Risk flags (is_vpn, is_tor, is_relay, is_hosting) are on paid plans. Free keys return geolocation + ASN only; those flags are omitted. Free is 1,000 requests per UTC calendar month, 1 request/second, for personal and non-commercial use. Paid plans start at $9/month (Starter: 100k requests, 10 req/s; Growth: $29 / 500k / 25 req/s; Scale: $79 / 2M / 50 req/s). No overage charges. Commercial use requires a paid plan.

Get the real client IP first

Behind Nginx, a load balancer or a CDN, the socket address is the proxy, not the visitor. In Express, set trust proxy to match your topology and use req.ip — never parse raw X-Forwarded-For yourself. The full setup is in Get the real client IP and country in Express. In FastAPI / Uvicorn, start with --proxy-headers --forwarded-allow-ips so request.client.host is the visitor. Strip the ::ffff: prefix from IPv4-mapped IPv6 addresses before you look the IP up.

The flags you will use

One GET /v0/ip/{ip} call with Authorization: Bearer returns location, network and traits. On a paid key, these are the traits that matter for traffic:

  • is_vpn — known VPN networks, including major commercial VPN providers.
  • is_tor — the IP is a current Tor exit node (exits only, not guards, middle relays or bridges).
  • is_relay — privacy relay egress. It is kept separate from is_vpn, so you don’t treat privacy-relay users like VPN users by mistake. See Detect iCloud Private Relay IPs.
  • is_hosting — hosting/datacenter detection: cloud, hosting and CDN networks where real users rarely browse from.

Behind a VPN, a Tor exit or a privacy relay, location is the egress, not the user’s. Use the flags as signals, not as a hard block: step up verification, tighten a rate limit or send a challenge, and keep going if the lookup fails.

Express middleware

Keep the key in NDL_API_KEY on the server. This helper caches per IP, times out at 800 ms and fails open. Attach it after trust proxy is set:

vpn-mw.js
// vpn-mw.js (Node 18+, global fetch)
const API = "https://api.networkdatalabs.com/v0/ip/";
const KEY = process.env.NDL_API_KEY;
const cache = new Map();            // swap for Redis/LRU in production
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;
}

function vpnTraffic() {
  return async (req, res, next) => {
    try {
      req.ipIntel = await lookup(normalize(req.ip));
    } catch {
      req.ipIntel = null;           // fail open: never block the request
    }
    next();
  };
}

module.exports = { vpnTraffic };
app.js
// app.js
const express = require("express");
const { vpnTraffic } = require("./vpn-mw");

const app = express();
app.set("trust proxy", 1);          // one reverse proxy; see the Express guide
app.use(vpnTraffic());

app.get("/account", (req, res) => {
  const t = req.ipIntel?.traits ?? {};
  // Step up on known VPN networks, Tor exits or hosting IPs.
  // Privacy relay (is_relay) is usually a normal user — log it, don't block.
  if (t.is_tor || t.is_vpn || t.is_hosting) {
    res.set("X-Step-Up", "verify");
  }
  res.json({ ok: true });
});

Python middleware (FastAPI / Starlette)

The same policy as an ASGI middleware. Tell Uvicorn which proxy to trust, then read request.state.ip_intel in the route. This is for request traffic, not for the signup allow / verify / review table in the Python signups guide.

vpn_mw.py
# vpn_mw.py
import os, time
from urllib.parse import quote
import httpx
from starlette.middleware.base import BaseHTTPMiddleware

API = "https://api.networkdatalabs.com/v0/ip/"
HEADERS = {"Authorization": f"Bearer {os.environ['NDL_API_KEY']}"}
_client = httpx.AsyncClient(timeout=httpx.Timeout(0.8), headers=HEADERS)
_cache: dict[str, tuple[float, dict]] = {}
TTL = 6 * 3600

def normalize(ip: str) -> str:
    return ip[7:] if ip and ip.startswith("::ffff:") else ip

async def lookup(ip: str) -> dict | None:
    hit = _cache.get(ip)
    if hit and hit[0] > time.time():
        return hit[1]
    try:
        r = await _client.get(API + quote(ip, safe=""))
        r.raise_for_status()
    except httpx.HTTPError:
        return None                  # fail open
    data = r.json()
    _cache[ip] = (time.time() + TTL, data)
    return data

class VpnTrafficMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        ip = request.client.host if request.client else ""
        request.state.ip_intel = await lookup(normalize(ip))
        return await call_next(request)
app.py
# app.py — FastAPI behind one trusted proxy
# uvicorn app:app --proxy-headers --forwarded-allow-ips="10.0.0.5"
from fastapi import FastAPI, Request
from vpn_mw import VpnTrafficMiddleware

app = FastAPI()
app.add_middleware(VpnTrafficMiddleware)

@app.get("/account")
async def account(request: Request):
    data = request.state.ip_intel
    t = (data or {}).get("traits") or {}
    step_up = bool(t.get("is_tor") or t.get("is_vpn") or t.get("is_hosting"))
    return {"ok": True, "step_up": step_up}

How to treat each flag

SignalWhat it meansSuggested action
is_torCurrent Tor exit nodeStep up or challenge; don’t hard-block unless you must
is_vpnKnown VPN networks, including major commercial VPN providersLog it; step up on sensitive paths (account, payment)
is_hostingHosting/datacenter IP: often scripts and botsTighter rate limit or a challenge
is_relayPrivacy relay: usually a normal, privacy-minded userAllow; don’t treat the location as precise

Example: 8.8.8.8 is hosting, not a VPN

A public US DNS resolver is a useful fixture. It should come back as US with is_hosting and is_anycast true, and is_vpn / is_tor / is_relay false. If your middleware would treat this IP as a VPN, the rule is too broad.

GET /v0/ip/{ip}
$ curl -s https://api.networkdatalabs.com/v0/ip/8.8.8.8 \
    -H "Authorization: Bearer YOUR_API_KEY" \
    | jq '{country_code: .location.country_code, traits}'

{
  "country_code": "US",
  "traits": {
    "is_anycast": true,
    "is_hosting": true,
    "is_mobile": false,
    "is_satellite": false,
    "is_bogon": false,
    "is_vpn": false,
    "is_tor": false,
    "is_relay": false
  }
}

Caching, timeouts and quota

  • Cache per IP for a few hours. Most traffic is repeat visitors, so the cache absorbs most lookups.
  • Skip paths that don’t need it — static assets, health checks — so you don’t spend quota on them.
  • Fail open on timeouts and errors; log that the lookup was unavailable.
  • Backfilling logs? Use POST /v0/bulk (paid plans) with up to 100 IPs per request. Each IP counts toward the monthly quota; a bad IP shows up under errors without failing the batch.

FAQ

Do I need a paid plan for this?

Yes, for the flags. Free keys omit is_vpn, is_tor, is_relay and is_hosting and return geolocation + ASN only, at 1,000 requests per UTC calendar month and 1 request/second, for personal and non-commercial use. Commercial use requires a paid plan. See the VPN detection API and pricing.

Can I hard-block every known VPN network?

You can, but it usually backfires. Plenty of real users come from a known VPN network or a privacy relay. Treat the flags as signals, add friction on sensitive paths, and leave is_relay alone unless you have a reason not to.

What about documentation IPs like 203.0.113.10?

Those TEST-NET addresses are reserved. The API returns them with traits.is_bogon true and no useful location. They’re fine for exercising fail-open; use a public US IP such as 8.8.8.8 when you want a real geolocation + traits fixture.

Why is the country “wrong” on a VPN?

You’re seeing the egress. The IP belongs to the known VPN network, the Tor exit or the privacy relay, so location.country_code is that exit’s country, not the user’s.

Related

Sign up Read the docs