New8 min read

AI Crawler Tracking

Understand the difference between AI crawlers and human AI referrals, track 39+ AI bots server-side, and capture exact #:~:text= cited passages.

Imtiaz Rayhan
Imtiaz RayhanCo-Founder & Lead Engineer, DotCamp & TrimStats
Verified against live TrimStats APIs
Quick reference

How do you track AI crawlers, AI referrals, and cited text passages in TrimStats?

Install the zero-dependency @trimstats/ai-crawl package in your Next.js proxy/middleware, Cloudflare Worker, or Express server to track GPTBot, ChatGPT-User, ClaudeBot, and Gemini crawlers without using monthly event quota. Human referrals from ChatGPT, Perplexity, Claude, and Gemini plus #:~:text= cited passages work automatically via t.js.

AI crawlers vs human AI referrals explained

AI traffic happens in two completely separate phases: automated bot fetches (when ChatGPT, Claude, or Perplexity fetches your raw HTML to train, index, or answer a prompt) and human AI referrals (when a real person clicks a citation link inside an AI answer and lands on your site).

Because most AI bots fetch raw HTML, robots.txt, llms.txt, and sitemaps without executing browser JavaScript, a client-side <script> tag alone cannot see them. TrimStats tracks human AI referrals automatically via t.js, and captures non-JS AI bots through POST https://collect.trimstats.com/v1/crawlers, Cloudflare sync, WordPress, or @trimstats/ai-crawl.

  • Crawler hits are stored in a dedicated crawler_events ClickHouse table so human visitors, sessions, bounce rates, and funnels stay completely isolated.
  • AI crawler traffic is excluded from your workspace monthly event quota (protected by a lightweight per-site rate cap against abuse).
  • Any headless AI crawler that does execute t.js and hits /v1/collect is automatically routed into crawler_events without inflating human metrics.
  • View daily multi-crawler trends, category totals (AI answers, Indexing, Training), and top crawled pages under Site analytics -> AI Traffic.
Zero latency impact on page responses

In Next.js and Cloudflare Workers, trackAiCrawler() uses event.waitUntil() / ctx.waitUntil() and pre-filters User-Agents locally in microseconds. Human browser requests trigger zero network calls.

Categories & supported crawlers

TrimStats classifies every incoming AI crawler User-Agent into one of three categories matching the dashboard tabs:

Site analytics / AI Traffic / Crawlers
Click any category card or provider row to see which URLs ChatGPT, Perplexity, Claude, or Gemini crawl most frequently, completely isolated from human traffic.
CategoryPurposeMatched User-Agents
AI answersLive page fetches triggered while an assistant answers a user promptChatGPT-User, Claude-User, Gemini-Deep-Research, Google-NotebookLM, Google-CloudVertexBot, Perplexity-User, DuckAssistBot, Amzn-User, NovaAct, Meta-ExternalFetcher, MistralAI-User, cohere-ai, Grok-DeepSearch
IndexingCrawlers indexing content for AI search and citation resultsOAI-SearchBot, Claude-SearchBot, GoogleOther, PerplexityBot, DuckDuckBot, Amzn-SearchBot, Amazonbot, Applebot, YouBot
TrainingFoundation model training and corpus collection botsGPTBot, ClaudeBot, Claude-Web, anthropic-ai, Google-Extended, Meta-ExternalAgent, FacebookBot, Applebot-Extended, cohere-training-data-crawler, GrokBot, xAI-Bot, Bytespider, TikTokSpider, CCBot, AI2Bot, Diffbot, Omgilibot

No-code setup: Cloudflare & WordPress

If you prefer not to add middleware code, TrimStats offers two zero-code integrations directly inside Site analytics -> AI Traffic -> Setup:

Cloudflare API Connect

No-code

Create a read-only Cloudflare API token (Zone -> Zone -> Read and Zone -> Analytics -> Read) and paste it in TrimStats. Works on Cloudflare Free plans, backfills 7 days immediately, and syncs hourly.

WordPress Plugin (.zip)

No-code

Download trimstats-analytics.zip, upload via Plugins -> Add New -> Upload Plugin, and enter your Site Public Key. Injects t.js automatically and reports AI crawlers server-side via non-blocking PHP requests.

Developer setup with @trimstats/ai-crawl

  1. 1

    Install the zero-dependency package

    Works in Next.js Edge/Node runtimes, Cloudflare Workers, Vercel, Netlify, Express, Bun, and Deno with zero sub-dependencies.

    BASH
    npm install @trimstats/ai-crawl
  2. 2

    Add 3 lines to your middleware or edge worker

    Pass your TrimStats site public key (pk_live_... from Site settings) and invoke trackAiCrawler() without await so responses return immediately.

1import { NextResponse, type NextFetchEvent, type NextRequest } from 'next/server';
2import { trackAiCrawler } from '@trimstats/ai-crawl';
3
4export function proxy(request: NextRequest, event: NextFetchEvent) {
5 trackAiCrawler(request, event, {
6 siteKey: 'pk_live_your_key',
7 });
8 return NextResponse.next();
9}
10
11export const config = {
12 matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
13};

Package options

siteKeystringRequired

Your site public key (pk_live_...), found under Site settings.

endpointstringOptionalDefault: https://collect.trimstats.com/v1/crawlers

Overrides the collector ingest URL (useful for self-hosted or proxied setups).

statusCodenumberOptionalDefault: 200

HTTP response status code to record (100 to 599). Automatically captured from res.statusCode in createAiCrawlerMiddleware.

countrystringOptionalDefault: auto-detected

Optional 2-letter ISO country code. Automatically read from request.cf.country, cf-ipcountry, x-vercel-ip-country, or cloudfront-viewer-country when omitted.

disableAiAnswers / disableIndexing / disableTrainingbooleanOptionalDefault: false

Opt out of forwarding specific crawler categories before any network request is made.

ignoreStaticAssetsbooleanOptionalDefault: true

Skips .js, .css, image, font, and media asset requests while keeping /robots.txt, /llms.txt, and XML sitemaps tracked.

timeoutMsnumberOptionalDefault: 3000

Abort timeout in milliseconds so background requests never hang.

Direct HTTP API & cURL test

Using PHP, Python, Go, Ruby, or Nginx? Send JSON directly to POST https://collect.trimstats.com/v1/crawlers as a single hit or a batch of up to 50 events. Non-AI User-Agents are ignored cleanly with HTTP 202 Accepted.

1curl -X POST 'https://collect.trimstats.com/v1/crawlers' \
2 -H 'content-type: application/json' \
3 -d '{
4 "s": "pk_live_your_key",
5 "u": "https://yourdomain.com/pricing",
6 "ua": "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; ChatGPT-User/1.0; +https://openai.com/bot",
7 "st": 200
8 }'
Allowed hostnames apply to crawler hits too

If your site defines Allowed hostnames in Site settings, POST /v1/crawlers only records URLs matching those hostnames or their subdomains.

AI referrals & cited passages (zero extra setup)

Switch to the AI Referrals & Citations tab on the AI Traffic page to measure human visitors clicking links inside AI assistants, along with attributed goals, revenue, and exact highlighted citation snippets. Everything in this tab works automatically with your existing t.js script.

Site analytics / AI Traffic / Referrals & Cited Passages
When an AI assistant links to your page using Chrome Scroll-to-Text-Fragment (#:~:text=), TrimStats captures the exact sentence highlighted for the visitor.
SignalHow TrimStats captures itWhat it shows
AI Assistant ReferralsMatches both referrer_domain and utm_source (for example chatgpt.com, perplexity.ai, claude.ai, gemini.google.com, copilot.microsoft.com, grok.com, meta.ai, chat.mistral.ai, deepseek.com, duck.ai)Daily visitor trends per assistant, top landing pages, goal conversion rates, and webhook-attributed revenue.
Cited Passages (`#:~:text=`)On initial page load, t.js reads W3C Scroll-to-Text-Fragment directives via performance.getEntriesByType('navigation') and sends them in the pageview beacon; the collector decodes and strips context prefixes/suffixes into props.cited_text.Exact quoted sentences and phrases that ChatGPT, Perplexity, or Google AI Overviews highlighted when linking visitors to your page.
Why user prompt text is not shown directly

AI platforms intentionally omit the user's raw prompt from HTTP headers and referrers for privacy. Pairing AI answers crawler hits with AI Referrals and Cited Passages (`#:~:text=`) shows which pages and exact quotes drive human clicks and conversions.

Common technical questions

Why cannot the t.js browser script track GPTBot or ChatGPT-User automatically?
Most AI crawlers fetch raw HTML, robots.txt, and llms.txt over HTTP without executing client-side JavaScript. Running @trimstats/ai-crawl at your server or edge captures those requests asynchronously with waitUntil and zero response delay.
Do AI crawler hits count toward my workspace monthly event quota?
No. AI crawler traffic is stored in a dedicated crawler_events table and excluded from your workspace monthly event quota, protected only by a lightweight per-site rate cap against abuse.
How does TrimStats capture #:~:text= cited passages without extra setup?
On initial page load, t.js inspects performance.getEntriesByType("navigation") for W3C Scroll-to-Text-Fragment directives (#:~:text=...) and attaches them to the pageview beacon, where the collector decodes the exact quoted phrase into props.cited_text.

Related guides