We raised $4M to scale our Agent-Led Growth Platform:Read more
Lightsage
All playbooks

Agent Analytics Setup

Get agent traffic tracking live on your docs in under an hour. This playbook walks you through installing the Lightsage middleware, verifying detection, and creating your first analytics dashboard.

30-60 minEngineers

Prerequisites

Make sure you have these before starting.

Hosting platform

Vercel, Cloudflare Pages, or any Node.js-compatible server

Lightsage account

The 7-day trial works for getting started

Access to your codebase

Ability to deploy middleware changes

What you'll do

1
5 min

Install Lightsage middleware

2
2 min

Configure environment variables

3
5 min

Verify agent detection is working

4
10 min

Set up conversion tracking

5
8 min

Create first dashboard

1

Install Lightsage middleware

~5 minutes

The Lightsage middleware runs at the edge and detects AI agent traffic by analyzing request headers and patterns. It adds minimal latency (typically under 5ms) and works with any JavaScript runtime.

Install the package

Terminal
npm install @lightsage/middleware

Or use yarn: yarn add @lightsage/middleware

Create the middleware file

Create a middleware.ts file in your project root (for Next.js) or the appropriate location for your framework.

middleware.ts
import { lightsage } from '@lightsage/middleware';

export const middleware = lightsage({
  publicKey: process.env.LIGHTSAGE_PUBLIC_KEY!,
});

export const config = {
  matcher: [
    // Match all paths except static files and API routes
    '/((?!_next/static|_next/image|favicon.ico|api/).*)',
  ],
};

Tip: The matcher configuration ensures the middleware only runs on content pages, not static assets. This keeps performance optimal.

2

Configure environment variables

~2 minutes

Get your public key from the Lightsage dashboard and add it to your environment configuration.

Get your public key

  1. Log in to the Lightsage dashboard
  2. Navigate to Settings > API Keys
  3. Copy your public key (starts with pk_)

Add to your environment

.env.local
LIGHTSAGE_PUBLIC_KEY=pk_live_your_key_here

Platform-specific configuration

Vercel

Add the environment variable in Project Settings > Environment Variables. Make sure to add it to all environments (Production, Preview, Development).

Cloudflare Pages

Add the variable in Settings > Environment variables. Use the wrangler CLI for local development: wrangler secret put LIGHTSAGE_PUBLIC_KEY

Self-hosted

Set the environment variable in your deployment configuration, Docker compose file, or server environment.

3

Verify agent detection is working

~5 minutes

After deploying, verify that the middleware is correctly detecting traffic. You can test this locally or in production.

Test locally with curl

Simulate an AI agent request to verify detection:

Terminal
# Simulate Claude Code user agent
curl -H "User-Agent: claudebot/1.0" http://localhost:3000/docs

# Simulate Cursor agent
curl -H "User-Agent: cursor-ai/1.0" http://localhost:3000/docs

# Simulate ChatGPT plugin
curl -H "User-Agent: ChatGPT-User" http://localhost:3000/docs

Check the Lightsage dashboard

  1. Open the Lightsage dashboard
  2. Navigate to Analytics > Real-time
  3. You should see your test requests appear within 30 seconds
  4. Verify the agent type is correctly identified

Enable debug mode (optional)

For troubleshooting, enable debug logging:

middleware.ts
export const middleware = lightsage({
  publicKey: process.env.LIGHTSAGE_PUBLIC_KEY!,
  debug: process.env.NODE_ENV === 'development',
});

Debug mode logs detected agents and attribution data to the console.

Checkpoint

At this point, you should see test requests in your Lightsage dashboard. If not, check the Troubleshooting section below.

4

Set up conversion tracking

~10 minutes

Connect agent visits to actual conversions like signups, API key generation, or purchases. This lets you attribute revenue to specific agents.

Install the client SDK

Terminal
npm install @lightsage/client

Track a signup conversion

Call trackConversion when a user completes a valuable action:

app/signup/page.tsx
import { trackConversion } from '@lightsage/client';

async function handleSignup(formData: FormData) {
  // Your existing signup logic
  const user = await createUser(formData);

  // Track the conversion
  await trackConversion({
    event: 'signup',
    userId: user.id,
    properties: {
      plan: 'free',
      source: 'docs',
    },
  });
}

Common conversion events

EventWhen to fire
signupUser creates an account
api_key_createdUser generates their first API key
first_api_callUser makes their first successful API request
upgradeUser upgrades to a paid plan

Server-side tracking (recommended for revenue)

For purchase events, use server-side tracking for accuracy:

app/api/webhooks/stripe/route.ts
import { Lightsage } from '@lightsage/node';

const lightsage = new Lightsage({
  secretKey: process.env.LIGHTSAGE_SECRET_KEY!,
});

export async function POST(req: Request) {
  const event = await parseStripeWebhook(req);

  if (event.type === 'checkout.session.completed') {
    await lightsage.trackConversion({
      event: 'purchase',
      userId: event.data.object.client_reference_id,
      revenue: event.data.object.amount_total / 100,
      currency: 'USD',
    });
  }
}
5

Create first dashboard

~8 minutes

Set up a dashboard to monitor agent traffic patterns and conversion attribution.

Key metrics to track

Agent Traffic Share

What percentage of your docs traffic comes from AI agents vs browsers?

Top Agents

Which agents visit most: Claude Code, Cursor, ChatGPT, Codex?

Top Pages

Which documentation pages do agents visit most frequently?

Conversion Rate

How often do agent sessions lead to signups vs browser sessions?

Create your first chart

  1. Go to Analytics > Dashboards in Lightsage
  2. Click Create Dashboard
  3. Add a Time Series chart
  4. Set metric to Page Views
  5. Group by Agent Type
  6. Set time range to Last 7 days

Set up alerts (optional)

Get notified when agent traffic patterns change significantly:

  • Alert when agent traffic share drops below 10%
  • Alert when a new agent type starts visiting
  • Weekly digest of agent traffic trends
You're done!

Agent analytics is now live. Give it 24-48 hours to collect meaningful data, then review your dashboard to understand how AI agents interact with your docs.

Platform-specific setup

Vercel (Next.js)

If you have existing middleware, compose them together:

middleware.ts
import { lightsage } from '@lightsage/middleware';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

const lightsageMiddleware = lightsage({
  publicKey: process.env.LIGHTSAGE_PUBLIC_KEY!,
});

export async function middleware(request: NextRequest) {
  // Run Lightsage first
  const response = await lightsageMiddleware(request);

  // Add your custom middleware logic
  // Example: Add security headers
  response.headers.set('X-Frame-Options', 'DENY');

  return response;
}

Cloudflare Pages

Use the Cloudflare-specific adapter for optimal edge performance:

functions/_middleware.ts
import { lightsageCloudflare } from '@lightsage/middleware/cloudflare';

export const onRequest = lightsageCloudflare({
  publicKey: env.LIGHTSAGE_PUBLIC_KEY,
});

Mintlify

Add the Lightsage script to your Mintlify configuration:

mint.json
{
  "integrations": {
    "lightsage": {
      "publicKey": "pk_live_your_key_here"
    }
  }
}

Note: Mintlify's built-in integration handles agent detection automatically. No middleware setup required.

Troubleshooting

No agent traffic showing up

  • Verify middleware is deployed and running
  • Check that LIGHTSAGE_PUBLIC_KEY is set correctly
  • Confirm the middleware file is in the correct location
  • Wait 2-3 minutes for data to appear in dashboard

Middleware conflicts with existing middleware

  • Ensure lightsage middleware runs first in the chain
  • Use the compose pattern shown in the Vercel section
  • Check for path conflicts in matcher config

High latency after adding middleware

  • Enable async mode: async: true in config
  • Check if your edge location is far from Lightsage servers
  • Verify you're using the edge-compatible package version

Conversions not being attributed

  • Ensure trackConversion is called after user action completes
  • Check that the same session ID is being used
  • Verify event names match your dashboard configuration

Still stuck? Check the Agent Analytics overview or contact support.

Ready to see your agent traffic?

Set up takes 30 minutes. Start tracking which AI agents visit your docs today.