Skip to content
iplogs.comSign up
Guide · Last updated 2026-11-19

VPN, proxy, and Tor detection in Node.js

Everything below runs on Node's built-in fetch and Express, written in TypeScript. It starts with response types and a fetch call with a timeout, then adds Express middleware, a per-IP cache (LRU or Redis), batch scoring through /v1/bulk-check, and tests that never touch the network. You won't need an API key or an account.

By Fizzah Mehtab ·

How do you add VPN detection to a Node.js app?

Use Node's built-in fetch and no dependencies. Call POST https://iplogs.com/v1/check with the body {"ip":"..."} and an AbortSignal.timeout of 10 seconds, slightly longer than the API's roughly 8-second probing ceiling. No API key or account is needed. Each IP gets 2,000 full checks a day at up to 60 requests a minute, and after that answers come from the fast in-memory path with no live probing. Type the response with a Verdict union of clean, suspicious, vpn_likely and vpn_detected so shape changes fail at compile time. Behind a proxy, set Express trust proxy to your proxy addresses and read req.ip, because anyone can send X-Forwarded-For. Put the call in Express middleware that stores the verdict on res.locals and fails open on errors, then let each route apply its own policy. Cache verdicts for five minutes with an LRU or Redis. Score queues through /v1/bulk-check at 100 addresses per request, and test with a mocked fetch.

Type the response

A few types declared up front catch shape drift at compile time and give you autocomplete in the editor:

export type Verdict =
  | "clean"
  | "suspicious"
  | "vpn_likely"
  | "vpn_detected";

export interface IPInfo {
  ip: string;
  asn?: string;
  org?: string;
  country?: string;
  country_code?: string;
  is_vpn?: boolean;
  vpn_provider?: string;
  vpn_provider_sources?: string[];
}

export interface Signal {
  type: string;
  weight: number;
  matched: boolean;
  detail: string;
}

export interface CheckResponse {
  verdict: Verdict;
  score: number;
  is_vpn: boolean;
  confidence: number;
  signals: Signal[];
  ip_info: IPInfo;
  request_id: string;
}

Quick start (built-in fetch + AbortSignal)

import type { CheckResponse } from "./types";

export async function checkVpn(ip: string): Promise<CheckResponse> {
  const r = await fetch("https://iplogs.com/v1/check", {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ ip }),
    signal: AbortSignal.timeout(10_000), // API stops probing at ~8s
  });
  if (!r.ok) throw new Error(`IPLogs HTTP ${r.status}`);
  return r.json() as Promise<CheckResponse>;
}

AbortSignal.timeout(10_000) caps a single call at ten seconds, so a slow upstream can't tie up a worker. The limit is set above the /v1/check server-side ceiling of around eight seconds on purpose. A new IP usually answers in about 2 seconds, but the slowest datacenter IPs take 5–7, and a five-second timeout would drop exactly those.

Reading the visitor IP from a trusted proxy

Behind a reverse proxy, the client IP arrives in X-Forwarded-For, and anyone can send that header. Tell Express which addresses are your proxies; req.ip then walks the header from the right and stops at the first address that isn't one of them.

import type { Request } from "express";

// Caddy or Nginx on the same host. Add a load balancer's address or
// subnet if there is one: app.set("trust proxy", ["loopback", "10.0.0.0/24"]).
// Behind Cloudflare, also list Cloudflare's ranges (cloudflare.com/ips).
app.set("trust proxy", "loopback");

export function clientIp(req: Request): string {
  return req.ip ?? "";
}

Express middleware

import type { Request, Response, NextFunction } from "express";
import { checkVpn } from "./check-vpn";
import { clientIp } from "./client-ip";
import type { CheckResponse } from "./types";

declare module "express-serve-static-core" {
  interface Locals { verdict?: CheckResponse }
}

export async function vpnVerdictMiddleware(
  req: Request,
  res: Response,
  next: NextFunction,
) {
  const ip = clientIp(req);
  if (!ip) return next();
  try {
    res.locals.verdict = await checkVpn(ip);
  } catch {
    // Fail open: leave verdict undefined; per-route handlers decide.
  }
  next();
}

// Per-route policy
app.post("/signup", vpnVerdictMiddleware, (req, res) => {
  const v = res.locals.verdict?.verdict;
  if (v === "vpn_detected") return res.status(403).end();
  if (v === "vpn_likely") return res.redirect("/signup/verify");
  return handleSignup(req, res);
});

Per-IP cache (in-process or Redis)

Cache each IP for 5 minutes. An in-process LRU is fine on a single instance. On a fleet, use Redis so every instance shares the same cache.

import { LRUCache } from "lru-cache";
import { checkVpn } from "./check-vpn";
import type { CheckResponse } from "./types";

const cache = new LRUCache<string, CheckResponse>({
  max: 10_000,
  ttl: 5 * 60 * 1000, // 5 minutes
});

export async function checkVpnCached(ip: string): Promise<CheckResponse> {
  const hit = cache.get(ip);
  if (hit) return hit;
  const v = await checkVpn(ip);
  cache.set(ip, v);
  return v;
}

For Redis, swap the LRU for ioredis and store the verdict as JSON with EX 300. Key on the bare IP, without a per-deploy prefix, so the cache survives rollouts.

Batch scoring with /v1/bulk-check

export interface BulkRow {
  ip: string;
  verdict: Verdict;
  score: number;
  is_vpn: boolean;
  vpn_provider?: string;
  country_code?: string;
  asn?: string;
  org?: string;
  error?: string;
}

export async function bulkCheck(ips: string[]): Promise<BulkRow[]> {
  const r = await fetch("https://iplogs.com/v1/bulk-check", {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ ips }),
    signal: AbortSignal.timeout(95_000), // server budget ~90s
  });
  if (!r.ok) throw new Error(`bulk HTTP ${r.status}`);
  const json = await r.json() as { results: BulkRow[] };
  return json.results;
}

// Chunk a larger list into batches of 100
export async function scoreQueue(allIps: string[]): Promise<Record<string, BulkRow>> {
  const out: Record<string, BulkRow> = {};
  for (let i = 0; i < allIps.length; i += 100) {
    const batch = await bulkCheck(allIps.slice(i, i + 100));
    for (const row of batch) out[row.ip] = row;
  }
  return out;
}

Testing without hitting the network

// vitest
import { describe, it, expect, vi, afterEach } from "vitest";
import { checkVpn } from "./check-vpn";

afterEach(() => vi.restoreAllMocks());

describe("checkVpn", () => {
  it("returns the verdict for a clean IP", async () => {
    vi.spyOn(globalThis, "fetch").mockResolvedValue(
      new Response(JSON.stringify({
        verdict: "clean",
        score: 0,
        is_vpn: false,
        confidence: 0.15,
        signals: [],
        ip_info: { ip: "1.1.1.1" },
        request_id: "req_test",
      })),
    );
    const out = await checkVpn("1.1.1.1");
    expect(out.verdict).toBe("clean");
  });
});

FAQ

Do I need an API key to use IPLogs from Node.js?

No. /v1/check is public and unauthenticated, so a plain fetch from any Node.js process works, with no signup or token. Each source IP gets 2,000 full-depth checks a day and 60 requests a minute. Once the daily 2,000 is used up, responses come from the in-memory fast path ("mode": "fast", no real-time probing). If you need more full-depth capacity, email admin@iplogs.com.

Should I use undici, axios, got, or the built-in fetch?

Use the built-in fetch (Node 18+) unless you have a reason not to. It ships with Node, supports AbortSignal.timeout, and is the same API browsers have. undici is the engine underneath and exposes connection-pooling primitives if you need them. axios and got mostly add features you won't use for one POST to one host.

Where should the IPLogs call live in an Express app?

Put it in an Express middleware that stores the verdict on res.locals.verdict, and let each route decide what to do with it. The network call then lives in one place, while the policy sits next to the route it applies to.

Does Next.js middleware support this kind of call?

Edge middleware can run fetch, so it works, but Edge has a tight time budget. It is cleaner to call /v1/check from a server component, a Route Handler or your Node.js backend and pass the verdict down through headers or context, instead of holding up Edge middleware on a network round trip.

How do I test the integration without hitting the network?

Mock fetch with vitest's vi.spyOn(globalThis, 'fetch'), or use undici's MockAgent if you want richer matching. The verdict shape is stable: verdict ('clean' | 'suspicious' | 'vpn_likely' | 'vpn_detected'), score (0–1), is_vpn, ip_info, signals[]. Assertions on the URL and body are enough to cover the integration.

The API docs describe the full response schema, and the Python guide covers the same integration for Python services. Published false-positive rates are on the accuracy benchmark. To see a real response, open the live IP checker in your browser.