Track Custom Events Without a Heavy Analytics Suite

Full analytics suites are great when you need funnels, cohorts, and dashboards. A lot of the time, though, I just want to know three things: did anyone click the signup button, did they finish the form, and which page sent them there.

For that, you can build a first-party tracker in about twenty lines.

The client

function track(name, props = {}) {
  const body = JSON.stringify({
    name,
    props,
    path: location.pathname,
    ts: Date.now(),
  });

  const sent = navigator.sendBeacon(
    "/events",
    new Blob([body], { type: "application/json" })
  );

  if (!sent) {
    fetch("/events", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body,
      keepalive: true,
    });
  }
}

navigator.sendBeacon is designed for this job. It queues the request so it survives page navigation, which a normal fetch might not.

Wire it up with data attributes

<button data-track="signup_click" data-track-plan="pro">Sign up</button>
document.addEventListener("click", (e) => {
  const el = e.target.closest("[data-track]");
  if (!el) return;
  track(el.dataset.track, { plan: el.dataset.trackPlan });
});

Now marketing can add events in HTML without touching JavaScript.

The server

import express from "express";
const app = express();

app.post("/events", express.json({ limit: "4kb" }), (req, res) => {
  const { name, props, path, ts } = req.body ?? {};
  if (typeof name !== "string" || name.length > 64) return res.sendStatus(400);
  // store it: append to a table, a queue, or a log line
  console.log(JSON.stringify({ name, props, path, ts }));
  res.sendStatus(204);
});

Validate input and cap the body size. This endpoint is public, so assume someone will send junk to it.

Keep it privacy-friendly

  • Don’t store IP addresses or cookies unless you truly need them.
  • Send event names and a few properties, not personal data.
  • Because it’s first party, you can describe exactly what you collect in your privacy policy.

What you give up

You won’t get sessions, attribution, or funnels for free. If you find yourself rebuilding those, it’s time to consider a purpose-built tool.

That gap, a lightweight custom-events tool that stays simpler than a full analytics suite, is what I’m exploring at Divertly. If you’d like to try it, get in touch.