{"id":49182923,"url":"https://github.com/apideck-libraries/agent-analytics-nextjs-starter","last_synced_at":"2026-04-23T02:04:47.352Z","repository":{"id":352369274,"uuid":"1214887773","full_name":"apideck-libraries/agent-analytics-nextjs-starter","owner":"apideck-libraries","description":"Next.js 15 starter that tracks AI agent traffic (ClaudeBot, GPTBot, Perplexity, and 20+ more) in PostHog. One-click deploy, sample Markdown-mirror docs routes, @apideck/agent-analytics wired in.","archived":false,"fork":false,"pushed_at":"2026-04-19T08:46:28.000Z","size":23,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-19T09:29:22.383Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://agent-analytics-nextjs-starter.vercel.app","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/apideck-libraries.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-04-19T07:23:20.000Z","updated_at":"2026-04-19T08:46:32.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/apideck-libraries/agent-analytics-nextjs-starter","commit_stats":null,"previous_names":["apideck-libraries/agent-analytics-nextjs-starter"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/apideck-libraries/agent-analytics-nextjs-starter","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/apideck-libraries%2Fagent-analytics-nextjs-starter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/apideck-libraries%2Fagent-analytics-nextjs-starter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/apideck-libraries%2Fagent-analytics-nextjs-starter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/apideck-libraries%2Fagent-analytics-nextjs-starter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/apideck-libraries","download_url":"https://codeload.github.com/apideck-libraries/agent-analytics-nextjs-starter/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/apideck-libraries%2Fagent-analytics-nextjs-starter/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32162614,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-22T17:06:48.269Z","status":"online","status_checked_at":"2026-04-23T02:00:06.710Z","response_time":53,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-04-23T02:04:24.181Z","updated_at":"2026-04-23T02:04:47.338Z","avatar_url":"https://github.com/apideck-libraries.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"---\nname: Agent Analytics Starter\nslug: agent-analytics-starter\ndescription: Track AI agent traffic (ClaudeBot, GPTBot, Perplexity, and 20+ more) in PostHog via middleware. Serves clean Markdown to agents on the same URLs — @apideck/agent-analytics wired in.\nframework: Next.js\nuseCase: Edge Middleware\ncss: Plain CSS\ndeployUrl: https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fapideck-libraries%2Fagent-analytics-nextjs-starter\u0026env=NEXT_PUBLIC_POSTHOG_KEY,NEXT_PUBLIC_POSTHOG_HOST\u0026envDescription=PostHog%20project%20API%20key%20and%20host\u0026envLink=https%3A%2F%2Fgithub.com%2Fapideck-libraries%2Fagent-analytics-nextjs-starter%23environment-variables\u0026project-name=agent-analytics-starter\u0026repository-name=agent-analytics-starter\ndemoUrl: https://agent-analytics-nextjs-starter.vercel.app\nrelatedTemplates:\n  - bot-protection-datadome\n  - bot-protection-botd\n---\n\n\u003cdiv align=\"center\"\u003e\n\n\u003cimg src=\"./public/hero.svg\" alt=\"Agent Analytics — see the agents your JavaScript can't.\" width=\"100%\" /\u003e\n\n# Agent Analytics — Next.js starter\n\n### Next.js 15 starter that tracks AI agent traffic in PostHog — drop in your API key, deploy, watch ClaudeBot show up in your dashboard.\n\n**One-click deploy.** Sample `/docs/` routes that serve as HTML to browsers and **clean Markdown to AI agents**. Every Markdown fetch fires a `doc_view` event with `is_ai_bot`, `source`, and `user_agent` — ready to segment in PostHog.\n\n[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fapideck-libraries%2Fagent-analytics-nextjs-starter\u0026env=NEXT_PUBLIC_POSTHOG_KEY,NEXT_PUBLIC_POSTHOG_HOST\u0026envDescription=PostHog%20project%20API%20key%20and%20host\u0026envLink=https%3A%2F%2Fgithub.com%2Fapideck-libraries%2Fagent-analytics-nextjs-starter%23environment-variables\u0026project-name=agent-analytics-starter\u0026repository-name=agent-analytics-starter)\n\n[**Live demo**](https://agent-analytics-nextjs-starter.vercel.app) · [**@apideck/agent-analytics**](https://github.com/apideck-libraries/agent-analytics) · [**The pattern, explained**](https://addyosmani.com/blog/agentic-engine-optimization/)\n\n\u003c/div\u003e\n\n---\n\n## What this template does\n\nAI crawlers don't run JavaScript — so your client-side analytics never see them. This template closes that gap:\n\n1. **`middleware.ts`** uses [`@apideck/agent-analytics`](https://www.npmjs.com/package/@apideck/agent-analytics) to detect 20+ known AI bots (ClaudeBot, GPTBot, PerplexityBot, Google-Extended, Applebot-Extended, Bytespider, Cursor, Windsurf, and more) and capture a `doc_view` event in PostHog on every request.\n2. **`/docs/` routes** are served as clean Markdown when an agent asks (via `.md` suffix, `Accept: text/markdown`, or a known bot UA) — otherwise HTML. Same URL, two representations.\n3. **Every Markdown response** carries `Content-Signal`, `Vary: accept`, and `x-markdown-tokens` headers so agents can budget context before parsing.\n\nRuns on Vercel's Fluid Compute. Zero infrastructure to manage, events land in PostHog seconds after deploy.\n\n## Quick start\n\n### 1. Deploy\n\nClick the Deploy button above, or:\n\n```bash\nnpx create-next-app --example https://github.com/apideck-libraries/agent-analytics-nextjs-starter my-app\ncd my-app\nvercel --prod\n```\n\n### 2. Set env vars\n\nIn the Vercel deploy prompt (or your project's env settings):\n\n| Variable | Required | Example |\n|---|---|---|\n| `NEXT_PUBLIC_POSTHOG_KEY` | yes | `phc_xxxxxxxx` — from PostHog project settings |\n| `NEXT_PUBLIC_POSTHOG_HOST` | no (defaults to US cloud) | `https://us.i.posthog.com`, `https://eu.i.posthog.com`, or your own reverse-proxy |\n\nIf `NEXT_PUBLIC_POSTHOG_KEY` is absent the middleware silently no-ops — nothing breaks, events just don't flow.\n\n### 3. Verify\n\n```bash\n# From your local terminal, pointed at the deployment:\ncurl -A \"ClaudeBot/1.0 probe-$(date +%s)\" https://\u003cyour-deployment\u003e.vercel.app/docs/intro\n```\n\nOpen PostHog → Activity and filter events by `event = doc_view`. You should see one event with `is_ai_bot: true`, `source: ua-rewrite`, and the probe UA you sent.\n\n---\n\n## How it works\n\n```\n Agent / Browser                 middleware.ts                    PostHog\n────────────────   ────────────────────────────────────────   ──────────\n      │                                                              │\n      │ GET /docs/intro                                               │\n      │ Accept: text/markdown (or .md suffix, or AI-bot UA)           │\n      ├──────────────────────┐                                        │\n      │                      ▼                                        │\n      │           markdownServeDecision(req) → reason                 │\n      │                      │                                        │\n      │     ┌────────────────┴───────────────┐                        │\n      │     ▼                                ▼                        │\n      │  trackDocView(req, {                NextResponse.rewrite(     │\n      │    analytics,                         req.nextUrl → /md/...   │\n      │    source: reason,                  )                         │\n      │    properties: {...}                                          │\n      │  }) ────fire-and-forget──────keepalive fetch──►───────────►   │\n      │                                                              │\n      │ ◄──── 200 text/markdown ────────────────                     │\n      │       Content-Signal, x-markdown-tokens                      │\n      │                                                              │\n```\n\nKey properties:\n\n- **Fire-and-forget** — the capture is non-blocking. `keepalive: true` lets it survive after the response returns.\n- **No person profiles** — `$process_person_profile: false` tells PostHog not to create one per unique bot fingerprint.\n- **Stable anon distinct_id** — djb2 hash of `ip:ua` collapses repeat fetches from the same agent into one visitor.\n\n## Structure\n\n```\n.\n├── middleware.ts               # The star of the show\n├── app/\n│   ├── layout.tsx\n│   ├── page.tsx                # Landing page with probe instructions\n│   ├── globals.css\n│   └── docs/[slug]/page.tsx    # Human-facing docs (HTML)\n├── public/\n│   ├── md/docs/\n│   │   ├── intro.md            # Agent-facing Markdown mirror\n│   │   └── usage.md\n│   └── llms.txt                # Agent-friendly site index\n├── .env.example\n├── package.json\n└── README.md\n```\n\n## Customising\n\n**Add a new `/docs/` page**:\n\n1. Create `public/md/docs/\u003cslug\u003e.md` — what agents see.\n2. Add an entry to the `DOCS` object in `app/docs/[slug]/page.tsx` — what browsers see.\n3. Update `public/llms.txt` so agents can discover it.\n\n**Extend the mirror to cover other routes** (e.g. `/blog/*`, `/guides/*`):\n\nEdit `resolveMirrorPath` in `middleware.ts`:\n\n```ts\nfunction resolveMirrorPath(pathname: string): string | null {\n  if (pathname.startsWith('/docs/')) return `/md${pathname}.md`\n  if (pathname.startsWith('/blog/')) return `/md${pathname}.md`   // ← add this\n  return null\n}\n```\n\nThen create matching `public/md/blog/*.md` files.\n\n**Swap analytics backends** — replace the PostHog adapter with a webhook, Mixpanel, or your own callback:\n\n```ts\nimport { trackDocView, webhookAnalytics } from '@apideck/agent-analytics'\n\nconst analytics = webhookAnalytics({\n  url: 'https://collector.example.com/events',\n  headers: { Authorization: `Bearer ${process.env.COLLECTOR_TOKEN}` }\n})\n```\n\nAny `{ capture(event) }` object is a valid adapter.\n\n## Environment variables\n\n\u003ca id=\"environment-variables\"\u003e\u003c/a\u003e\n\n| Variable | Description |\n|---|---|\n| `NEXT_PUBLIC_POSTHOG_KEY` | PostHog project API key (the public key used by the JS SDK). Find it under *Project settings → Project API Key*. |\n| `NEXT_PUBLIC_POSTHOG_HOST` | PostHog ingestion host. Defaults to `https://us.i.posthog.com`. Set to `https://eu.i.posthog.com` for EU cloud, or your own reverse-proxy domain (e.g. `https://svc.example.com`) to dodge ad-blockers. |\n\n## Learn more\n\n- [`@apideck/agent-analytics` on GitHub](https://github.com/apideck-libraries/agent-analytics) — the library powering this template\n- [Agentic Engine Optimization](https://addyosmani.com/blog/agentic-engine-optimization/) — the case for agent-ready docs sites\n- [contentsignals.org](https://contentsignals.org) — the `Content-Signal` header spec\n- [developers.apideck.com](https://developers.apideck.com) — the production docs site this pattern was extracted from\n\n## License\n\nMIT © Apideck\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fapideck-libraries%2Fagent-analytics-nextjs-starter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fapideck-libraries%2Fagent-analytics-nextjs-starter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fapideck-libraries%2Fagent-analytics-nextjs-starter/lists"}