DEV Community

Cover image for How to count unique visitors without cookies (with code)
linkbe
linkbe

Posted on Edited on AI-assisted

How to count unique visitors without cookies (with code)

Disclosure: I work on FastAnalytics, a cookieless analytics tool. This post explains the general technique used by most privacy-friendly analytics tools. You can build a simple version yourself with the code below.

"How do you count unique visitors if you don't use cookies?" is the first question everyone asks about cookieless analytics. The answer is surprisingly simple, and it comes with one honest trade-off.

Let's build it.


The problem

With cookies, counting unique visitors is easy: you store a random ID in the browser the first time someone visits, and read it back every time after that.

Without cookies (or localStorage, or anything else stored on the device), every request looks anonymous. You still get a few things from each HTTP request:

  • the IP address,
  • the User-Agent header,
  • the page URL and the referrer.

The trick is to turn those into a temporary, anonymous identifier that is stable for a short time and then becomes useless.

The technique: a daily rotating salted hash

visitor_id = hash(daily_salt + site_id + ip + user_agent)
Enter fullscreen mode Exit fullscreen mode
  • daily_salt is a random secret generated once per day and deleted after the day is over.
  • site_id makes the same person get different IDs on different websites, so nobody can follow them across sites.
  • ip + user_agent make the ID stable for the same browser on the same network during the day.

Because the salt is random and thrown away, nobody (including you) can recompute yesterday's IDs or reverse the hash back into an IP address. You never store the IP itself.

A minimal implementation in Node.js

Here's a small Express endpoint that receives pageviews and counts daily unique visitors.

// server.js
import express from "express";
import crypto from "node:crypto";

const app = express();
// sendBeacon sends text/plain to avoid a CORS preflight, so accept both
app.use(express.json({ type: ["application/json", "text/plain"] }));
app.set("trust proxy", true); // if you run behind a proxy/CDN

// --- Daily salt -----------------------------------------------------------
let currentDay = null;
let salt = null;

function getSalt() {
  const today = new Date().toISOString().slice(0, 10); // UTC date
  if (today !== currentDay) {
    currentDay = today;
    salt = crypto.randomBytes(32).toString("hex"); // old salt is discarded
  }
  return salt;
}

// --- Anonymous visitor id ---------------------------------------------------
function visitorId(siteId, ip, userAgent) {
  return crypto
    .createHash("sha256")
    .update(getSalt() + siteId + ip + userAgent)
    .digest("hex")
    .slice(0, 16);
}

// --- Very small in-memory store (use a real database in production) -------
const stats = new Map(); // key: `${day}|${siteId}` -> { pageviews, visitors:Set }

app.post("/collect", (req, res) => {
  const { siteId, path, referrer } = req.body || {};
  if (!siteId || !path) return res.sendStatus(400);

  const ua = req.get("user-agent") || "";
  if (/bot|crawl|spider|slurp|preview/i.test(ua)) return res.sendStatus(204);

  const id = visitorId(siteId, req.ip, ua); // req.ip is used here and never stored
  const key = `${currentDay}|${siteId}`;

  if (!stats.has(key)) stats.set(key, { pageviews: 0, visitors: new Set() });
  const s = stats.get(key);
  s.pageviews += 1;
  s.visitors.add(id);

  res.sendStatus(204);
});

app.get("/stats/:siteId", (req, res) => {
  getSalt(); // make sure currentDay is set
  const s = stats.get(`${currentDay}|${req.params.siteId}`);
  res.json({
    day: currentDay,
    pageviews: s ? s.pageviews : 0,
    uniqueVisitors: s ? s.visitors.size : 0,
  });
});

app.listen(3000, () => console.log("Listening on http://localhost:3000"));
Enter fullscreen mode Exit fullscreen mode

The tracking script

On the website, a few lines are enough. No cookies, no storage:

<script>
  (function () {
    function send() {
      var body = JSON.stringify({
        siteId: "my-site",
        path: location.pathname,
        referrer: document.referrer || null,
      });
      if (navigator.sendBeacon) {
        navigator.sendBeacon(
          "https://your-domain.com/collect",
          new Blob([body], { type: "text/plain" })
        );
      } else {
        fetch("https://your-domain.com/collect", {
          method: "POST",
          headers: { "Content-Type": "text/plain" },
          body: body,
          keepalive: true,
        });
      }
    }
    send();
  })();
</script>
Enter fullscreen mode Exit fullscreen mode

sendBeacon is ideal here: it's fire-and-forget and survives the page being closed.

For single-page apps, call send() again on every route change (for example, by wrapping history.pushState or using your router's navigation hook).


What you gain

  • Nothing stored on the visitor's device. No cookies, no localStorage, no fingerprint saved anywhere.
  • No IP addresses in your database. They're used in memory for a few microseconds and dropped.
  • No cross-site tracking. The siteId in the hash makes IDs different on every site.
  • No long-term profiles. Tomorrow's salt is new, so tomorrow's IDs can't be linked to today's.

What you give up (the honest part)

  • Returning visitors across days. The same person on Monday and Friday counts as two daily visitors. Your "monthly unique visitors" will be higher than in a cookie-based tool, because it's closer to a sum of daily uniques.
  • Some precision within a day. Two people on the same office network with identical browsers may be counted as one. A person switching from Wi-Fi to mobile data becomes two visitors.
  • User-level journeys over weeks, cross-device tracking and advertising audiences. That's the whole point, but be aware of it.

For most websites, the question "how many people visited, from where, and what did they read?" matters far more than "is this the same person as three weeks ago?". That's where this approach shines.


Going further

A production-grade version also needs:

  • Better bot filtering (known bot lists, headless browser detection, rate limits).
  • Approximate geolocation done before discarding the IP (country and city only, never storing the address).
  • Session logic (for example, a 30-minute inactivity window per visitor ID) to compute bounce rate and visit duration.
  • Salt storage that works across multiple servers and is deleted reliably (for example, in Redis with an expiry).
  • A legal review. Whether you need consent also depends on your jurisdiction and on everything else your site loads.

If you'd rather not build and maintain all that, tools like Plausible, Umami, Fathom, Simple Analytics and FastAnalytics do it for you, each with slightly different choices.


Have you built your own analytics? I'd like to hear what you did about bots. That's always the hardest part.

Cover photo by Gabriel Heinzer on Unsplash.

Top comments (0)