Track AI crawlers server-side

Most crawlers, including GPTBot, ClaudeBot and Bytespider, never run JavaScript, so a script on your pages misses them. Report every crawler request from your server or CDN instead: a few lines for Cloudflare, Next.js, Node.js or PHP, or the WordPress plugin.

Why server-side

A JavaScript tracker only sees visitors that run JavaScript. Search engines render some pages, but most AI crawlers, scrapers and link preview bots download the HTML and leave.

Your server sees every request: pages, robots.txt, llms.txt, sitemaps and PDFs, with the real status code and the IP address needed to verify the crawler.

Reports are sent after the response, so visitors do not wait for them.

How it works

The code checks each request's user agent with a short pattern and skips static files. Requests that may come from a crawler are sent to NMOS.NET with the user agent, IP address, URL and status code.

Each report is signed with your site key (HMAC-SHA256), so nobody else can send data for your site. Keep the key in an environment variable or secret, never in the code.

NMOS.NET identifies the crawler with the same catalog as the rest of the dashboard, verifies its IP address and ignores everything that is not a crawler. A visit seen by both the server and the page script is counted once.

Before you start

You need your tracking ID and site key. Both are on app.nmos.net under Integrations (Pro+), and the site key is also under My Websites. Replace YOUR_TRACKING_ID in the code; put the site key in NMOS_SITE_KEY.

Cloudflare Worker

  1. In Cloudflare, open Workers & Pages and create a Worker. Paste the code below.
  2. Under Settings → Variables and Secrets, add a secret named NMOS_SITE_KEY with your site key.
  3. Add a route for your site (example.com/*) and deploy. The Worker also adds the tracking tags to HTML pages.
// NMOS.NET crawler tracking for Cloudflare Workers. Route: your-site.com/*
// 1. Paste this as the Worker code.  2. Settings > Variables and Secrets: add a Secret named
//    NMOS_SITE_KEY with your site key.  3. Add the route and deploy.
// Every crawler request is reported from the edge (also bots that never run JavaScript), and the
// tracking tags are added to HTML pages for human traffic.
const TRACKING_ID = "YOUR_TRACKING_ID";
const INGEST = "https://ingest.nmos.net";
const MAYBE_BOT = /bot|crawl|spider|slurp|fetch|scrap|preview|agent|archiv|index|monitor|check|scan|search|http|python|curl|wget|java|go-|okhttp|axios|node|headless|lighthouse|pagespeed|ggpht|compatible;/i;
const ASSET = /\.(?:css|js|mjs|map|png|jpe?g|gif|webp|avif|svg|ico|woff2?|ttf|otf|eot|mp4|webm|mp3)$/i;

export default {
  async fetch(request, env, ctx) {
    const response = await fetch(request);
    const ua = request.headers.get("user-agent") || "";
    if (env.NMOS_SITE_KEY && ua && (!/mozilla/i.test(ua) || MAYBE_BOT.test(ua)) && !ASSET.test(new URL(request.url).pathname)) {
      ctx.waitUntil(report(env.NMOS_SITE_KEY, {
        ua: ua.slice(0, 1000),
        ip: request.headers.get("cf-connecting-ip") || "",
        url: request.url.slice(0, 2000),
        status: response.status,
      }).catch(() => {}));
    }
    const type = response.headers.get("content-type") || "";
    if (!type.includes("text/html") || !response.body) return response;
    return new HTMLRewriter()
      .on("head", {
        element(head) {
          head.append(`<meta name="nmos-tracking" content="${TRACKING_ID}">`, { html: true });
          head.append(`<script src="${INGEST}/tracking.js" async></script>`, { html: true });
          head.append(`<link rel="stylesheet" href="${INGEST}/v1/beacon.css?tid=${encodeURIComponent(TRACKING_ID)}&status=${response.status}">`, { html: true });
        },
      })
      .transform(response);
  },
};

async function report(key, data) {
  const body = JSON.stringify(data);
  const ts = String(Math.floor(Date.now() / 1000));
  const enc = new TextEncoder();
  const k = await crypto.subtle.importKey("raw", enc.encode(key), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  const mac = new Uint8Array(await crypto.subtle.sign("HMAC", k, enc.encode(ts + "." + body)));
  const sig = "sha256=" + Array.from(mac, (b) => b.toString(16).padStart(2, "0")).join("");
  await fetch(INGEST + "/v1/server-report", {
    method: "POST",
    headers: { "content-type": "application/json", "x-nmos-site": TRACKING_ID, "x-nmos-timestamp": ts, "x-nmos-signature": sig },
    body,
  });
}

Next.js (Vercel, Netlify, self-hosted)

  1. Save the code as middleware.ts in your project root, next to app/ or pages/. If you already have a middleware, call nmosReport(request, event) from it.
  2. Set the environment variable NMOS_SITE_KEY in your hosting settings and redeploy.
  3. The middleware runs before the page, so the status code is recorded as 200.
// NMOS.NET crawler tracking for Next.js (Vercel, Netlify or self-hosted): save as middleware.ts in
// the project root (next to app/ or pages/) and set the environment variable NMOS_SITE_KEY to your
// site key. If you already have a middleware, call nmosReport(request, event) inside it.
import { NextResponse, type NextFetchEvent, type NextRequest } from 'next/server';

const TRACKING_ID = 'YOUR_TRACKING_ID';
const INGEST = 'https://ingest.nmos.net';
const MAYBE_BOT = /bot|crawl|spider|slurp|fetch|scrap|preview|agent|archiv|index|monitor|check|scan|search|http|python|curl|wget|java|go-|okhttp|axios|node|headless|lighthouse|pagespeed|ggpht|compatible;/i;

export function middleware(request: NextRequest, event: NextFetchEvent) {
  nmosReport(request, event);
  return NextResponse.next();
}

export const config = {
  matcher: ['/((?!_next/static|_next/image|.*\\.(?:css|js|map|png|jpe?g|gif|webp|avif|svg|ico|woff2?|ttf)$).*)'],
};

export function nmosReport(request: NextRequest, event: NextFetchEvent) {
  const key = process.env.NMOS_SITE_KEY;
  const ua = request.headers.get('user-agent') ?? '';
  if (!key || !ua || (/mozilla/i.test(ua) && !MAYBE_BOT.test(ua))) return;
  const ip = request.headers.get('x-real-ip') ?? request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ?? '';
  // The middleware runs before the page, so the status is not known here; it is recorded as 200.
  event.waitUntil(send(key, { ua: ua.slice(0, 1000), ip, url: request.url.slice(0, 2000) }).catch(() => {}));
}

async function send(key: string, data: Record<string, string>) {
  const body = JSON.stringify(data);
  const ts = String(Math.floor(Date.now() / 1000));
  const enc = new TextEncoder();
  const k = await crypto.subtle.importKey('raw', enc.encode(key), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
  const mac = new Uint8Array(await crypto.subtle.sign('HMAC', k, enc.encode(`${ts}.${body}`)));
  const sig = 'sha256=' + Array.from(mac, (b) => b.toString(16).padStart(2, '0')).join('');
  await fetch(`${INGEST}/v1/server-report`, {
    method: 'POST',
    headers: { 'content-type': 'application/json', 'x-nmos-site': TRACKING_ID, 'x-nmos-timestamp': ts, 'x-nmos-signature': sig },
    body,
  });
}

Node.js (Express)

  1. Save the code as nmos-tracking.js and add app.use(nmosTracking) before your routes.
  2. Set NMOS_SITE_KEY in the environment. Behind a proxy or load balancer, enable app.set('trust proxy', true) so the visitor's IP address is used.
  3. Works with Node.js 18 or later; other frameworks with (req, res, next) middleware work the same way.
// NMOS.NET crawler tracking for Node.js (Express, or any framework with (req, res, next) middleware).
// Node 18+. Set the environment variable NMOS_SITE_KEY to your site key, then: app.use(nmosTracking);
// Behind a proxy or load balancer, set app.set('trust proxy', true) so req.ip is the visitor's address.
const crypto = require('node:crypto');

const TRACKING_ID = 'YOUR_TRACKING_ID';
const INGEST = 'https://ingest.nmos.net';
const MAYBE_BOT = /bot|crawl|spider|slurp|fetch|scrap|preview|agent|archiv|index|monitor|check|scan|search|http|python|curl|wget|java|go-|okhttp|axios|node|headless|lighthouse|pagespeed|ggpht|compatible;/i;
const ASSET = /\.(?:css|js|mjs|map|png|jpe?g|gif|webp|avif|svg|ico|woff2?|ttf|otf|eot|mp4|webm|mp3)$/i;

function nmosTracking(req, res, next) {
  const key = process.env.NMOS_SITE_KEY;
  const ua = req.get('user-agent') || '';
  if (key && ua && (!/mozilla/i.test(ua) || MAYBE_BOT.test(ua)) && !ASSET.test(req.path)) {
    res.on('finish', () => {
      const body = JSON.stringify({
        ua: ua.slice(0, 1000),
        ip: (req.ip || '').replace(/^::ffff:/, ''),
        url: `${req.protocol}://${req.get('host')}${req.originalUrl}`.slice(0, 2000),
        status: res.statusCode,
      });
      const ts = String(Math.floor(Date.now() / 1000));
      const sig = 'sha256=' + crypto.createHmac('sha256', key).update(`${ts}.${body}`).digest('hex');
      fetch(`${INGEST}/v1/server-report`, {
        method: 'POST',
        headers: { 'content-type': 'application/json', 'x-nmos-site': TRACKING_ID, 'x-nmos-timestamp': ts, 'x-nmos-signature': sig },
        body,
        signal: AbortSignal.timeout(3000),
      }).catch(() => {});
    });
  }
  next();
}

module.exports = { nmosTracking };

PHP

  1. Save the code as nmos-tracking.php and include it at the top of your front controller, for example index.php.
  2. Set NMOS_SITE_KEY in the environment (or in your server configuration).
  3. With PHP-FPM the report is sent after the page has gone to the visitor.
<?php
// NMOS.NET crawler tracking for PHP sites (PHP 7.4+ with cURL). Include this file at the top of your
// front controller (e.g. index.php) and set the environment variable NMOS_SITE_KEY to your site key
// (or replace getenv('NMOS_SITE_KEY') with the key). WordPress: use the NMOS Crawl Tracking plugin.
// The report is sent after the page has gone to the visitor (PHP-FPM), so it does not slow pages down.
const NMOS_TRACKING_ID = 'YOUR_TRACKING_ID';
const NMOS_MAYBE_BOT = '/bot|crawl|spider|slurp|fetch|scrap|preview|agent|archiv|index|monitor|check|scan|search|http|python|curl|wget|java|go-|okhttp|axios|node|headless|lighthouse|pagespeed|ggpht|compatible;/i';

register_shutdown_function(function () {
    $key = getenv('NMOS_SITE_KEY');
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
    if (!$key || $ua === '' || (stripos($ua, 'mozilla') !== false && !preg_match(NMOS_MAYBE_BOT, $ua))) {
        return;
    }
    $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
    $body = json_encode([
        'ua' => substr($ua, 0, 1000),
        // Behind a proxy or CDN, use the address it forwards, but only if every request passes through it.
        'ip' => $_SERVER['REMOTE_ADDR'] ?? '',
        'url' => substr(($https ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? '') . ($_SERVER['REQUEST_URI'] ?? '/'), 0, 2000),
        'status' => http_response_code() ?: 200,
    ]);
    if (function_exists('fastcgi_finish_request')) {
        fastcgi_finish_request();
    }
    $ts = (string) time();
    $ch = curl_init('https://ingest.nmos.net/v1/server-report');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $body,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 3,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'X-NMOS-Site: ' . NMOS_TRACKING_ID,
            'X-NMOS-Timestamp: ' . $ts,
            'X-NMOS-Signature: sha256=' . hash_hmac('sha256', $ts . '.' . $body, $key),
        ],
    ]);
    curl_exec($ch);
    curl_close($ch);
});

WordPress

Install the NMOS Crawl Tracking plugin from WordPress.org, paste your tracking ID, and add the site key under Settings → Site key to turn on server-side reports.

NMOS Crawl Tracking on WordPress.org

Any other server (HTTP API)

Send one POST request per crawler visit to https://ingest.nmos.net/v1/server-report with a JSON body {"ua", "ip", "url", "status"} (8 KB at most) and three headers: X-NMOS-Site (your tracking ID), X-NMOS-Timestamp (Unix seconds, within 5 minutes) and X-NMOS-Signature (sha256= followed by the hex HMAC-SHA256 of timestamp + "." + body, keyed with your site key).

# NMOS.NET server report from any language: sign "<timestamp>.<body>" with HMAC-SHA256 and your
# site key, then POST it. One request per crawler visit; non-crawler user agents are ignored.
KEY="$NMOS_SITE_KEY"
BODY='{"ua":"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)","ip":"66.249.66.1","url":"https://example.com/page","status":200}'
TS=$(date +%s)
SIG=$(printf '%s.%s' "$TS" "$BODY" | openssl dgst -sha256 -hmac "$KEY" -hex | sed 's/^.* //')
curl -s https://ingest.nmos.net/v1/server-report \
  -H 'Content-Type: application/json' \
  -H 'X-NMOS-Site: YOUR_TRACKING_ID' \
  -H "X-NMOS-Timestamp: $TS" \
  -H "X-NMOS-Signature: sha256=$SIG" \
  --data "$BODY"

Questions

Does it slow my site down?
No. The report is sent after the response (waitUntil on Cloudflare and Vercel, the finish event in Node.js, fastcgi_finish_request in PHP) and only for requests that may come from a crawler.
Are human visitors sent to NMOS.NET?
The code filters by user agent first, so almost all human requests stay on your server. Anything that still arrives and is not a known crawler is discarded without being stored.
Do I still need the page script?
Server-side reports cover crawlers. The page script adds human traffic, devices and referrers. You can use both: a visit reported twice is counted once.

How crawler visits are verified · Look up a user agent

See every crawler that visits your site

Free account, a few lines of code, and every crawler request shows up in your dashboard, verified.