DEV Community

Mason K
Mason K

Posted on

Build a video view counter that ignores autoplay, refreshes and bots

TL;DR

Counting play events counts muted autoplay, refreshes and bots as viewers. We'll build a tracker that counts a view only when the player is at least 50% on screen, playing, in a visible tab, for 2 continuous seconds (the MRC video viewability floor), plus a Node server that dedupes per viewer and drops bots with isbot. In a scripted test, the naive counter said 5 and the real one said 1.

Why play is the wrong event 🎥

There's no universal definition to copy. YouTube doesn't publish its organic threshold, Shorts counts every start since March 2025, Facebook reports "Views" and 3-second plays separately, and LinkedIn ads use 2 continuous seconds at 50% visible. (Swydo, updated Nov 2026, Blck Alpaca)

So we'll pick a definition on purpose. The MRC viewable impression guideline for video ads (50% of pixels, 2 continuous seconds) is a sensible floor:

Condition How we detect it
At least 50% on screen IntersectionObserver with a 0.5 threshold
Actually playing playing / pause / waiting / ended events
Tab is visible document.visibilityState
2 continuous seconds timer that resets if any condition breaks
Not a repeat server dedupe per viewer + video + 30 min window
Not a bot isbot on the user agent, server-side

Stack: Node 22, isbot 5.2.4, no framework. Tested in Chromium 158 with Playwright.

1. The client tracker

// public/view-tracker.js
// A "view" = the player was >= 50% on screen, actually playing, in a visible tab,
// for QUALIFY_MS of continuous time. One view per element per page load.
const QUALIFY_MS = 2000;

export function trackViews(video, { videoId, endpoint = '/api/view' }) {
  let onScreen = false, playing = false, counted = false;
  let streakStart = null, timer = null;

  const pageVisible = () => document.visibilityState === 'visible';
  const qualifying = () => onScreen && playing && pageVisible();

  function update() {
    if (counted) return;
    if (qualifying() && streakStart === null) {
      streakStart = performance.now();
      timer = setTimeout(fire, QUALIFY_MS);
    } else if (!qualifying() && streakStart !== null) {
      clearTimeout(timer);           // streak broken: MRC-style "continuous"
      streakStart = null;
    }
  }

  function fire() {
    counted = true;
    const body = JSON.stringify({ videoId, viewerId: viewerId(), ts: Date.now() });
    navigator.sendBeacon(endpoint, new Blob([body], { type: 'application/json' }));
  }

  new IntersectionObserver(([e]) => { onScreen = e.intersectionRatio >= 0.5; update(); },
    { threshold: [0, 0.5, 1] }).observe(video);
  video.addEventListener('playing', () => { playing = true; update(); });
  for (const ev of ['pause', 'waiting', 'ended', 'emptied'])
    video.addEventListener(ev, () => { playing = false; update(); });
  document.addEventListener('visibilitychange', update);
}

function viewerId() {
  try {
    let id = localStorage.getItem('vid_viewer');
    if (!id) { id = crypto.randomUUID(); localStorage.setItem('vid_viewer', id); }
    return id;
  } catch { return 'anon'; }
}
Enter fullscreen mode Exit fullscreen mode

A few choices worth calling out:

  • playing, not play. play fires when playback is requested; playing fires when frames are actually moving. A stall (waiting) breaks the streak.
  • The streak resets. Scroll away at 1.9 s and you start again from zero. That's what "continuous" means.
  • sendBeacon survives the page unloading, so a view that qualifies right before navigation still arrives.

💡 Tip: for long-form content, consider a second, higher-threshold event (say "engaged view" at 30 s). Keep names distinct so nobody mixes them up on a dashboard.

2. The server: dedupe and bots 🛠️

npm i isbot
Enter fullscreen mode Exit fullscreen mode
// server.mjs
import http from 'node:http';
import { readFile } from 'node:fs/promises';
import { isbot } from 'isbot';

const DEDUPE_MS = 30 * 60 * 1000;          // one view per viewer per video per 30 min
const lastCounted = new Map();             // `${viewerId}:${videoId}` -> ts (use Redis in prod)
export const stats = { received: 0, bot: 0, duplicate: 0, counted: 0, naivePlays: 0 };

const server = http.createServer(async (req, res) => {
  if (req.method === 'POST' && req.url === '/api/view') {
    let raw = ''; for await (const c of req) raw += c;
    stats.received++;
    const ua = req.headers['user-agent'] ?? '';
    if (isbot(ua)) { stats.bot++; return res.writeHead(204).end(); }
    const { videoId, viewerId } = JSON.parse(raw);
    const key = `${viewerId}:${videoId}`, now = Date.now();
    if (now - (lastCounted.get(key) ?? 0) < DEDUPE_MS) { stats.duplicate++; return res.writeHead(204).end(); }
    lastCounted.set(key, now); stats.counted++;
    return res.writeHead(204).end();
  }
  if (req.method === 'POST' && req.url === '/api/naive-play') { stats.naivePlays++; return res.writeHead(204).end(); }
  if (req.url === '/stats') return res.writeHead(200, {'content-type':'application/json'}).end(JSON.stringify(stats));
  const path = req.url === '/' ? '/feed.html' : req.url;
  try {
    const body = await readFile('public' + path);
    const type = path.endsWith('.js') ? 'text/javascript' : path.endsWith('.mp4') ? 'video/mp4' : 'text/html';
    res.writeHead(200, { 'content-type': type }).end(body);
  } catch { res.writeHead(404).end(); }
});
server.listen(3000, () => console.log('listening on :3000'));
Enter fullscreen mode Exit fullscreen mode

⚠️ Note: the static file handler is demo-only (no path sanitizing). Don't ship it. In production, the dedupe map belongs in Redis with a TTL, and viewerId should come from your auth session when you have one.

3. A feed page that runs both counters

Three muted autoplaying videos: two at the top, one far below the fold. Each gets the real tracker and a naive play counter so we can compare.

<!-- public/feed.html -->
<!doctype html><meta name=viewport content="width=device-width">
<style>video{display:block;width:480px;height:270px;margin:0 0 40px}.spacer{height:3000px}</style>
<video id=a src="/long.mp4" muted autoplay playsinline loop></video>
<video id=b src="/long.mp4" muted autoplay playsinline loop></video>
<div class=spacer></div>
<video id=c src="/long.mp4" muted autoplay playsinline loop></video>
<script type=module>
import { trackViews } from '/view-tracker.js';
for (const v of document.querySelectorAll('video')) {
  trackViews(v, { videoId: v.id });
  v.addEventListener('play', () => navigator.sendBeacon('/api/naive-play'), { once: true });
}
</script>
Enter fullscreen mode Exit fullscreen mode

4. Simulate real traffic with Playwright

Scenario: a viewer loads the feed, scrolls 300 px after 1 s (video a leaves the screen), refreshes, and then a headless bot visits.

// run.js
const { chromium } = require('playwright');
const stats = async p => (await (await p.request.get('http://localhost:3000/stats')).json());
(async () => {
  const b = await chromium.launch();
  const human = await b.newContext({ userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36', viewport:{width:1280,height:720} });
  const p = await human.newPage();
  await p.goto('http://localhost:3000/');
  await p.waitForTimeout(1000);
  await p.evaluate(() => window.scrollTo(0, 300));      // video "a" drops below 50% visible after 1s
  await p.waitForTimeout(3000);
  console.log('after first visit  ', JSON.stringify(await stats(p)));
  await p.reload(); await p.waitForTimeout(3000);
  console.log('after reload       ', JSON.stringify(await stats(p)));
  const bot = await (await b.newContext()).newPage();   // default HeadlessChrome UA
  await bot.goto('http://localhost:3000/'); await bot.waitForTimeout(3000);
  console.log('after headless UA  ', JSON.stringify(await stats(bot)));
  console.log('default UA was:', await bot.evaluate(() => navigator.userAgent));
  await b.close();
})();
Enter fullscreen mode Exit fullscreen mode
$ node server.mjs &
listening on :3000
$ node run.js
after first visit   {"received":1,"bot":0,"duplicate":0,"counted":1,"naivePlays":2}
after reload        {"received":2,"bot":0,"duplicate":1,"counted":1,"naivePlays":3}
after headless UA   {"received":4,"bot":2,"duplicate":1,"counted":1,"naivePlays":5}
default UA was: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/158.0.8127.36 Safari/537.36
Enter fullscreen mode Exit fullscreen mode

5. Reading the results 📊

Scenario Naive play Qualified views
First visit +2 (a and b started) +1 (b only; a was on screen ~1 s)
Reload +1 +0 (arrived, rejected as duplicate)
Headless bot +2 +0 (2 arrived, rejected by isbot)
Total 5 1

Two things I didn't expect:

  1. Video c never started. Chromium didn't autoplay the muted video while it was 3000 px offscreen, so even the naive counter skipped it. That's browser behavior you shouldn't rely on; a taller viewport or a different browser could start it.
  2. My own test harness is a bot. Playwright's default UA contains HeadlessChrome, which isbot flags. If your synthetic monitoring hits pages with view tracking, it's either inflating your counts (naive) or silently filtered (this setup). Set a real UA in tests that need to count, and know which one you're doing.

Things to know

  • Keep both numbers. Rename the naive count to "starts" and keep it. The gap between starts and views tells you how much of your autoplay gets real attention.
  • UA filtering is the floor. It catches honest automation. If views affect payouts, add rate limits per IP/viewer and anomaly checks.
  • Not tested here: the visibilitychange path (background tabs), Safari, mobile. The harness is headless Chromium 158 on one machine.

What's next

  • Send videoId, viewerId and a session id with every beacon into a real events table, then compute views in SQL so you can change the definition later and backfill.
  • Add an "engaged view" at a longer threshold and plot it next to views per video. The videos where the two diverge most are the ones worth a look.

Top comments (0)