start for free
start for free

<- playbooks / 00 · capturing visitor IPsBefore playbook 01

Capture your visitors' IPs request to IP to visits table

Your server already sees every visitor's IP address. This guide shows how to read it correctly, keep the ones worth looking up, and store them so playbook 01 can take it from there.

capture options
3
filters
4
columns to store
3

Playbook 01 starts from an IP address you already have. This is how you get one: read it on your server, drop the visits that can’t be a prospect, and keep the rest.

By the end

You’ll have a table of real visitor IPs, each with the page they viewed and when, with bots and your own team filtered out.

visitspostgres

=> select ip, path, visited_at from visits;

ippathvisited_at

203.0.113.10/pricing09:14:02

198.51.100.7/demo09:21:47

2001:db8::4f/features09:33:10

(3 rows)

=>

Pick one whichever matches how your site is hosted

First

Why the IP has to come from your server

Read the IP on a server you control, from a source your host vouches for. JavaScript in the browser can’t see the visitor’s public IP, and asking a third-party “what’s my IP” service from the page adds a dependency, gets blocked by ad blockers, and can be faked.

Your server sees the address of whatever connected to it last. If your site sits behind a CDN, load balancer or edge platform, that’s the proxy, not the visitor. The proxy passes the real address along in a request header.

  1. Visitor203.0.113.10the one you want
  2. CDN or load balancer172.70.42.9adds a header
  3. Your server sees

    socket 172.70.42.9 ✗ the proxy

    header 203.0.113.10 ✓ the visitor

Where your host puts it

  • CloudflareCF-Connecting-IPheader
  • VercelipAddress(request)from @vercel/functions
  • Netlify Edge Functionscontext.ip
  • Your own server behind a proxyreq.ipin Express, once trust proxy is set

X-Forwarded-For

Don’t read it yourself unless you have to.

It can hold a chain of addresses, and anything a client sends in it arrives untouched at the first hop, so the left-most entry is easy to fake. Cloudflare’s own guidance is to use CF-Connecting-IP instead, because it holds exactly one address.

IPv6 is fine. ip_to_company accepts IPv4 and IPv6 addresses, so store whatever your host gives you. If you use Cloudflare’s Pseudo IPv4 setting, read the real address from CF-Connecting-IPv6.

Next: 01 Read it at the edge

Option 1

Read it at the edge

If your site already runs through Cloudflare or Netlify, an edge function can log every page view without touching your app. It sits in front of your pages, passes each request through, and records the visitor on the way.

Each example calls recordVisit(), your own function that writes one row to wherever you store visits (see 05 store).

worker.js · on a route that covers your site

export default {
  async fetch(request, env, ctx) {
    const response = await fetch(request); // pass through to your site

    const isPage = request.method === "GET" &&
      (request.headers.get("Accept") || "").includes("text/html");

    if (isPage) {
      ctx.waitUntil(recordVisit(env, {
        ip: request.headers.get("CF-Connecting-IP"),
        path: new URL(request.url).pathname,
        userAgent: request.headers.get("User-Agent"),
        ts: new Date().toISOString(),
      }));
    }

    return response;
  },
};

ctx.waitUntil()

Lets the write finish after the page has gone back to the visitor, so logging adds no delay.

text/html

Both examples only log HTML page views, so images, scripts and fonts don’t each count as a visit.

On Vercel? Read the address with ipAddress(request) from @vercel/functions in whichever function handles the visit. The simplest setup is the beacon in option 3, with its collector deployed as a Vercel Function.

Next: 02 Read it in your app server

Option 2

Read it in your app server

If you run your own Node server, a few lines of middleware log each page view. The one setting that matters is trust proxy. Without it, Express reports the address of your load balancer for every visitor.

server.js

import express from "express";

const app = express();

// One proxy or load balancer in front of the app.
// Use its IP instead of 1 if it's fixed.
app.set("trust proxy", 1);

app.use((req, res, next) => {
  if (req.method === "GET" && req.accepts("html")) {
    recordVisit({
      ip: req.ip,
      path: req.path,
      userAgent: req.get("User-Agent"),
      ts: new Date().toISOString(),
    }).catch(() => {}); // never let logging break a page
  }
  next();
});
CDN → load balancer → app

The request arrives with

  • X-Forwarded-For192.0.2.66, 203.0.113.10, 172.70.42.9
  • socket10.0.4.12

app.set("trust proxy", 2)

req.ip 203.0.113.10

The visitor. One for each proxy in front of the app.

Set the number to how many proxies sit in front of the app: 1 for a single load balancer, 2 if a CDN sits in front of that. Avoid true. Express warns that true takes the left-most X-Forwarded-For entry, which a client can set to anything unless your last proxy overwrites it.

Check it. Log req.ip once from your own browser and compare it with your public IP. If you see an internal address, such as one starting 10. or 192.168., the setting is too low.

Next: 03 A one-line tracking beacon

Option 3

A one-line tracking beacon

If your site runs on a builder such as Webflow, WordPress or HubSpot, where you can’t add server code, put a tiny script on the page and a small collector somewhere you can run code.

The script tells the collector which page was viewed. The collector reads the IP from the request, exactly as in options 1 and 2, because that’s the only trustworthy source.

The beacon · footer or GTM tag

<script>
  navigator.sendBeacon(
    "https://collect.yoursite.com/visit",
    JSON.stringify({ path: location.pathname })
  );
</script>

sendBeacon() sends a small POST in the background and doesn’t hold up the page. It sets no cookies.

The collector · Vercel Function

import { ipAddress } from "@vercel/functions";

export default {
  async fetch(request: Request) {
    if (request.method !== "POST") {
      return new Response(null, { status: 405 });
    }

    let body = {};
    try { body = JSON.parse(await request.text()); } catch {}

    await recordVisit({
      ip: ipAddress(request),
      path: String(body.path || "").slice(0, 500),
      userAgent: request.headers.get("User-Agent"),
      ts: new Date().toISOString(),
    });

    return new Response(null, { status: 204 });
  },
};

On Cloudflare, the same collector reads CF-Connecting-IP. On Netlify, it reads context.ip.

Two things keep it reliable

  • 1st party

    Serve the collector from your own domain.

    Use something like collect.yoursite.com. Ad and tracker blockers are much more likely to block a request to a third-party analytics domain.

  • { ?? }

    Treat the body as untrusted.

    Anyone can post to the collector, so cap the length of each field and never take the IP from the body.

Next: 04 Filter before you store

From our sister company

An IP gets you the company. RB2B gets you the person.

RB2B identifies the individual on your site, with their name, LinkedIn profile and business email, and sends them to Slack, Teams, your CRM or Clay. Person-level identification covers US visitors.

Try RB2B >One script in your site header.

Whichever option you picked

Filter before you store

Every IP you keep is a lookup you may pay for later, so drop the ones that can’t be a prospect at capture time. Four filters do most of the work.

Switch the filters on and off

Today’s page views
  1. 203.0.113.10/pricingChrome 131look up
  2. 192.0.2.80/Googlebot/2.1bot
  3. 198.51.100.20/blogChrome 131team
  4. 10.0.4.12/demoFirefox 133private
  5. 203.0.113.10/demoChrome 131repeat
  6. 198.51.100.7/pricingSafari 18look up
  7. 192.0.2.81/(none)bot
  8. 2001:db8::4f/featuresEdge 131look up
  9. 192.0.2.90/UptimeRobot/2.0bot
  10. 198.51.100.7/blogSafari 18repeat

3 of 10 to send to ip_to_company

A starting point

Call it at the top of recordVisit().

worthKeeping()

const BOT_UA = /bot|crawl|spider|slurp|preview|headless|lighthouse|monitor|curl|wget|python-requests/i;
const TEAM_IPS = new Set(["198.51.100.20", "198.51.100.21"]); // your office and VPN exits
const PRIVATE = /^(10\.|127\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|::1$|f[cd][0-9a-f]{2}:)/i;

function worthKeeping({ ip, userAgent }) {
  if (!ip || !userAgent) return false;
  if (BOT_UA.test(userAgent)) return false;
  if (TEAM_IPS.has(ip)) return false;
  if (PRIVATE.test(ip)) return false;
  return true;
}

Honest bots only

The list catches crawlers that announce themselves. Bots that pretend to be browsers will get through. If your site is on Cloudflare, its bot detection can catch more of those.

Home and mobile

You can’t filter out consumer traffic in advance. Home broadband, mobile networks and VPNs mostly come back from ip_to_company as not_found, which playbook 01 already handles.

Next: 05 What to store

Then

What to store, and for how long

Store three things per visit: the IP, the page, and the time. That’s all playbook 01 needs, and the less you keep, the less you have to protect.

A Postgres table is enough

create table visits (
  id          bigserial primary key,
  ip          inet not null,
  path        text not null,
  visited_at  timestamptz not null default now()
);

create index on visits (ip, visited_at);

The page matters as much as the IP.

  • /pricingstrong
  • /demostrong
  • /featuresmedium
  • /blog/...weak

A visit to /pricing or /demo is a stronger signal than one to a blog post, and later parts of your pipeline can use it to decide who to alert on. Keep the User-Agent only if you need it for debugging the bot filter.

Set a retention period and stick to it

Once an IP has been looked up, keep the company it resolved to and delete the raw address after your cache window. Playbook 01 uses 7 to 30 days.

  1. Day 0, capture203.0.113.10Personal data
  2. Look upacmeinfolabs.comBusiness data
  3. KeepCompany + pageBusiness data
  4. Day 7 to 30Raw IP deletedGone

Personal data from the first row.

An IP address can count as personal data under GDPR, so this table is personal data from the first row. Before you switch capture on:

  1. 01Say it in your privacy policy

    Say that you record visitor IPs and match them to companies, why, and how long you keep them.

  2. 02Check your consent banner

    If you use the beacon and have EU visitors, check whether your consent banner needs to cover it. In the EU, consent remains the default for non-essential tracking.

  3. 03Read playbook 01’s privacy chapter

    Read privacy and compliance before you contact anyone it finds.

This is a starting point, not legal advice. Check your setup with your own counsel.

Next: hand the IPs to playbook 01

Next

Hand the IPs to the playbook

On a schedule, every hour or once a day, pull the IPs you haven’t looked up yet and send them to ip_to_company in batches. One call takes up to 100 addresses, though each still counts as one request against your Fair Use limit.

Run this playbook on MoltSets

1,000 API calls. No card.

Sign up and start calling the API today.

summarise with AI

Put this page to work

Pick your AI. It opens with a ready prompt to summarise this page and apply it to your team.

ChatGPT Claude Google AI Mode Grok Perplexity