Documentation

Everything you need to integrate SourceBeam with AI agents, CLI tools, and custom applications.

Quick start

Get reliable analytics data in 4 steps:

  1. Install the tracking script on every route you want counted.
  2. Verify that SourceBeam sees your first real pageview on the deployed site.
  3. Optionally connect Stripe for revenue sync and attribution.
  4. Generate an API read token in Site Settings and call the API.
terminal
curl -H "Authorization: Bearer YOUR_TOKEN" \
  "https://srcbeam.com/api/ai?siteId=YOUR_SITE_ID"

That returns all your analytics data as AI-optimized JSON — human-readable timestamps, durations, and percentages.

Important: Load sb.js on every route you want counted, not only on pages where you call sourcebeam.goal(), sourcebeam.track(), or sourcebeam.revenue(). If the script is route-gated, SourceBeam shows partial visitors and pageviews because excluded pages do not exist in the dataset.

Installation

The default recommendation is simple: install SourceBeam everywhere. Use selective route loading only if you intentionally want partial analytics.

Recommended setup: put sb.js in the shared base template, root layout, or global head so it covers the whole site and only loads once.

Generic HTML install:

HTML
<script defer src="https://srcbeam.com/sb.js" data-site="YOUR_SITE_ID"></script>

Next.js App Router install:

app/layout.tsx
import Script from "next/script";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>{children}</body>
      <Script
        src="https://srcbeam.com/sb.js"
        data-site="YOUR_SITE_ID"
        strategy="afterInteractive"
      />
    </html>
  );
}

Installation rules

  • Load sb.js on every route you want counted. If a route does not load the script, its visitors and pageviews do not exist in SourceBeam.
  • If you use Next.js App Router, put the script in app/layout.tsx so it is shared across the site and only loads once.
  • If you call sourcebeam.track(...), sourcebeam.goal(...), or sourcebeam.revenue(...), the script must already be present on that page.
  • Stripe attribution is separate from visitor tracking. First make pageviews reliable, then connect Stripe.

Verification

Do not stop after adding the snippet. A tracking install is only real once you see SourceBeam receive an actual pageview from the deployed site.

Verification checklist

  • Open the homepage and one inner page on the deployed site, not just localhost.
  • Confirm /sb.js loads in the browser network panel on both pages.
  • Run window.sourcebeam?.getVisitorId?.() in the console and make sure it returns a value.
  • Refresh the SourceBeam dashboard and verify that pageviews or visitors increase after your own test visit.
  • If the dashboard only shows some routes, your install is partial, not site-wide.

Common failure modes

  • The script is route-gated, so only pricing, checkout, or blog pages are tracked.
  • The snippet was added to a page component instead of the shared root layout or base template.
  • A thank-you or return page is excluded, so Stripe success-page attribution never runs.
  • sourcebeam.goal(...) or sourcebeam.track(...) is called on a page that does not load sb.js.
  • The script works locally but is missing on production because the layout or template differs there.
Browser console
window.sourcebeam?.getVisitorId?.()
window.sourcebeam?.getSessionId?.()

Authentication

Two authentication methods are supported:

Bearer token (recommended for API/AI)

Generate a read-only token in Site Settings. Pass it via the Authorization header.

Authorization: Bearer sb_read_...

Session cookie

Automatic when logged in via the browser. Used by the dashboard.

AI API

The unified AI endpoint consolidates all analytics data into a single request. The AI agent selects which sections it needs.

GET/api/ai

Without siteId, returns a full markdown instruction file for AI agents — self-documenting API.

Parameters

siteIdstringrequired
Your site ID
sectionsstring
Comma-separated list: summary, overview, chart, pages, sources, devices, realtime, visitors, sessions, goals. Omit for all.
periodstring
today, 24h, 7d (default), 30d, 90d, 12m, all
timezonestring
IANA timezone, e.g. Europe/Warsaw
limitnumber
Max results for visitors/sessions (default 50)
offsetnumber
Pagination offset for visitors/sessions
Example: overview + pages for last 30 days
curl -H "Authorization: Bearer $TOKEN" \
  "https://srcbeam.com/api/ai?siteId=abc123&sections=overview,pages&period=30d"
Response
{
  "_meta": {
    "siteId": "abc123",
    "period": "30d",
    "from": "2024-02-25T00:00:00.000Z",
    "to": "2024-03-26T00:00:00.000Z",
    "sections": ["overview", "pages"],
    "generatedAt": "2024-03-26T12:00:00.000Z"
  },
  "overview": {
    "visitors": 1234,
    "sessions": 1890,
    "pageviews": 4500,
    "bounceRate": "45%",
    "avgDuration": "2m 15s",
    "revenue": 1250.00,
    "revenuePerVisitor": 1.01,
    "prev": {
      "visitors": 1100,
      "sessions": 1650,
      "pageviews": 3900,
      "bounceRate": "48%",
      "avgDuration": "1m 58s",
      "revenue": 980.00,
      "revenuePerVisitor": 0.89
    }
  },
  "pages": {
    "pages": [
      {
        "path": "/pricing",
        "title": "Pricing",
        "views": 340,
        "uniqueVisitors": 280,
        "avgTimeOnPage": "1m 30s",
        "revenue": 500.00
      }
    ],
    "unattributedRevenue": 120.00
  }
}

Sections

summary

A plain-text narrative summary of the analytics data. Ready to present to a user without further processing. Automatically fetches overview, pages, sources, devices, and realtime data to compose the summary even if those sections aren't explicitly requested.

"In the last 7 days, the site had 1,234 visitors, 1,890 sessions, and 4,500 pageviews.
Bounce rate: 45%. Average session duration: 2m 15s.
Revenue: $1,250.
Visitors are up 12% compared to the previous period (1,100 → 1,234).
Top pages: Pricing (340 views, $500), Blog (280 views), Home (250 views).
Top traffic sources: Direct (300 visitors), google.com (500 visitors).
Currently 3 active visitors on the site."

overview

Key metrics for the period with previous period comparison. Bounce rate includes % sign, duration is human-readable (e.g. 2m 15s).

chart

Time-series array. Auto-bucketed by period (hourly for today/24h, daily for 7d/30d, weekly for 90d, monthly for 12m/all).

[{"date": "2024-03-25T00:00:00.000Z", "visitors": 120, "sessions": 150, "revenue": 45.00}]

pages

Top 20 pages by views. Includes unattributedRevenue— Stripe revenue that couldn't be linked to a specific landing page.

sources

Traffic split into referrers (domains), utmSources (campaigns), and direct traffic. Each with visitor, session, and revenue counts. Also includes unattributedRevenue.

devices

Four arrays: countries, browsers, os, devices. Each entry has name, visitors, and revenue.

realtime

Current activeVisitors count and currentPages showing which pages are being viewed right now.

visitors

Paginated visitor list. ISO 8601 timestamps for firstSeen/lastSeen. Includes device, browser, OS, country, language, and session count.

sessions

Paginated session list. Duration is human-readable. Includes entry/exit pages, referrer, UTM data, bounce status, and page count. Internal fields (user agent, screen size) are stripped.

goals

Conversion goals configured for the site: id, name, type, and match configuration.

MCP Server

Connect SourceBeam to Claude Desktop, Cursor, Windsurf, or any MCP-compatible client. The MCP server exposes 8 tools that AI agents can call directly.

Claude Desktop

Add to ~/Library/Application Support/Claude/claude_desktop_config.json:

claude_desktop_config.json
{
  "mcpServers": {
    "sourcebeam": {
      "command": "npx",
      "args": ["tsx", "/path/to/sourcebeam/mcp/server.ts"],
      "env": {
        "SRCBEAM_API_URL": "https://srcbeam.com",
        "SRCBEAM_TOKEN": "your-api-token"
      }
    }
  }
}

Cursor

Add to .cursor/mcp.json in your project root:

.cursor/mcp.json
{
  "mcpServers": {
    "sourcebeam": {
      "command": "npx",
      "args": ["tsx", "/path/to/sourcebeam/mcp/server.ts"],
      "env": {
        "SRCBEAM_API_URL": "https://srcbeam.com",
        "SRCBEAM_TOKEN": "your-api-token"
      }
    }
  }
}

Claude Code

terminal
claude mcp add sourcebeam -- npx tsx /path/to/sourcebeam/mcp/server.ts

Available tools

ToolDescription
list_sitesList all your sites
get_analyticsFetch any analytics section
get_realtimeLive visitor count + active pages
compare_periodsCurrent vs previous period metrics
get_visitorFull visitor history and conversions
get_sessionFull session event timeline
create_goalCreate a conversion goal
export_dataExport raw data as JSON

CLI

Query analytics from the terminal. The CLI calls the /api/ai endpoint and formats the output for the terminal.

terminal
# Set your credentials
export SRCBEAM_TOKEN=your-api-token
export SRCBEAM_SITE=your-site-id

# Get a natural-language summary
npx tsx cli/srcbeam.ts summary

# Overview metrics for last 30 days
npx tsx cli/srcbeam.ts overview --period=30d

# Top pages
npx tsx cli/srcbeam.ts pages

# Live visitors
npx tsx cli/srcbeam.ts realtime

# Pipe into an LLM
npx tsx cli/srcbeam.ts overview --json | claude "Analyze this data"

# Everything at once
npx tsx cli/srcbeam.ts all --period=7d

Commands

CommandDescription
summaryNatural-language analytics summary
overviewKey metrics (visitors, sessions, bounce rate, revenue)
pagesTop pages by views
sourcesTraffic sources (referrers, UTM, direct)
devicesCountries, browsers, OS, device types
realtimeCurrently active visitors
sessionsRecent session list
goalsConversion goals
allEverything at once

Options

--periodstring
Time range: today, 24h, 7d (default), 30d, 90d, 12m, all
--sitestring
Site ID (or set SRCBEAM_SITE env var)
--jsonflag
Output raw JSON instead of formatted text. Useful for piping into other tools.

Which method do I use?

Your checkout redirects to a Stripe-hosted payment page?

You call stripe.checkout.sessions.create() on your server and redirect the user to the returned URL. This is the most common setup for SaaS, e-commerce, and one-time payments.

Use Checkout API →server-side

You have a custom payment form on your own page?

You use Stripe Elements, an embedded card form, or call stripe.paymentIntents.create() directly. The user never leaves your site during checkout.

Use Payment Intent →server-side

You share a Stripe Payment Link (no code)?

You created a Payment Link in the Stripe dashboard and share it on your website, email, or social media. No backend code involved.

Use Payment Links →success page

Not sure? Check your code — if you see stripe.checkout.sessions.create, use Checkout API. If you see stripe.paymentIntents.create, use Payment Intent. If you don't write any Stripe code, you're using Payment Links.

First make pageview tracking reliable across the site. Then connect your Stripe API key in site settings and add attribution.

Stripe Checkout

server-side attributionrecommended

For sites using Stripe's Checkout Session API. This is the most reliable path when your server attaches SourceBeam metadata to the Stripe flow and checkout only starts after the tracker is ready.

Works for one-time payments and subscription checkouts. If your app has upgrades, return pages, or post-checkout sync logic, keep those flows intact and verify the final paid Stripe object still carries attribution metadata.

Step 1: Backend

When creating the Checkout Session, include sb_visitor and sb_session in the metadata:

app/api/create-checkout/route.js
import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

export async function POST(request) {
  const { sbMeta } = await request.json();

  const session = await stripe.checkout.sessions.create({
    line_items: [{ price: "price_xxx", quantity: 1 }],
    mode: "payment",
    success_url: "https://yoursite.com/thank-you",
    metadata: {
      sb_visitor: sbMeta?.sb_visitor,
      sb_session: sbMeta?.sb_session,
    },
  });

  return Response.json({ url: session.url });
}

Step 2: Frontend

Before the checkout request, wait briefly for the tracker and send the metadata to your backend:

Frontend
async function getSourcebeamStripeMetadata(timeoutMs = 1500) {
  const startedAt = Date.now();

  while (Date.now() - startedAt < timeoutMs) {
    const sbMeta = window.sourcebeam?.getStripeMetadata?.();
    if (sbMeta) return sbMeta;
    await new Promise((resolve) => setTimeout(resolve, 50));
  }

  return undefined;
}

const sbMeta = await getSourcebeamStripeMetadata();

const res = await fetch("/api/create-checkout", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ sbMeta }),
});

const { url } = await res.json();
window.location.href = url;

SourceBeam uses this metadata during Stripe sync to match revenue back to the visitor who paid. No extra webhook is required for attribution itself.

Before you mark this done

  • Checkout creation still happens on the server.
  • The frontend does not rely on a one-shot window.sourcebeam?.getStripeMetadata() read.
  • The checkout request forwards sbMeta to the backend unchanged.
  • The paid Stripe flow still carries sb_visitor and sb_session.
  • Existing auth, return URLs, pricing, and billing behavior remain unchanged.

Payment Intent

server-side attribution

For custom checkout flows using Stripe Elements or the PaymentIntent API. Same idea as Checkout: create the payment object on the server and attach SourceBeam metadata there.

Step 1: Backend

app/api/create-payment-intent/route.js
import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

export async function POST(request) {
  const { amount, sbMeta } = await request.json();

  const paymentIntent = await stripe.paymentIntents.create({
    amount,
    currency: "usd",
    metadata: {
      sb_visitor: sbMeta?.sb_visitor,
      sb_session: sbMeta?.sb_session,
    },
  });

  return Response.json({ clientSecret: paymentIntent.client_secret });
}

Step 2: Frontend

Frontend
const sbMeta = await getSourcebeamStripeMetadata();

const res = await fetch("/api/create-payment-intent", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ amount: 2000, sbMeta }),
});

const { clientSecret } = await res.json();
// Pass clientSecret to Stripe Elements

Metadata flows through the PaymentIntent to the eventual charge, as long as your existing payment flow keeps using that server-created object.

Before you mark this done

  • PaymentIntent creation still happens on the server.
  • The frontend waits briefly for SourceBeam metadata before starting payment.
  • Your backend receives and forwards sbMeta without changing the rest of the payload.
  • The Stripe object SourceBeam sync reads still exposes sb_visitor and sb_session.
  • No confirmation, webhook, or capture logic regresses.
success-page attributionno code

For Stripe Payment Links, do not paste a checkout snippet into your app. This is a Stripe dashboard setup plus a tracked return page on your site.

  1. Go to your Stripe Payment Link settings
  2. Open the After payment tab
  3. Set the confirmation page to redirect to your website with the session ID:
https://yoursite.com/thank-you?session_id={CHECKOUT_SESSION_ID}

SourceBeam's tracker automatically detects ?session_id=cs_xxx in the URL and attributes the payment to the visitor. Make sure sb.js is loaded on the thank-you page.

Before you mark this done

  • Your Payment Link redirects back to your own domain.
  • The redirect URL includes session_id={CHECKOUT_SESSION_ID} exactly.
  • The return page loads sb.js and is not excluded from tracking.
  • You did not add unnecessary backend Stripe code for this flow.
  • The same success path works for every Payment Link you actually use.

Why "success-page" instead of server-side? Payment Links rely on the tracker being loaded on the success page. If the visitor has JavaScript disabled, an aggressive adblocker, or closes the browser before the success page loads, attribution is lost. For a server-side path, use Checkout API or PaymentIntent API with server-side metadata.

Duplicate payment events are ignored — no need to worry about multiple page loads on the success URL.

llms.txt

SourceBeam serves a standard llms.txt file at the root domain for AI agent discovery.

GET /llms.txt
# SourceBeam

> Privacy-friendly website analytics with AI-ready API.

## API
- AI Analytics API: https://srcbeam.com/api/ai

AI agents and frameworks that follow the llms.txt convention will automatically discover your API and its documentation.

Endpoints

These individual endpoints are also available. The dashboard uses them directly. For AI/CLI use, the unified /api/ai endpoint is recommended instead.

MethodPathDescription
GET/api/analytics/overviewKey metrics + chart + previous period
GET/api/analytics/pagesTop pages
GET/api/analytics/sourcesTraffic sources
GET/api/analytics/devicesBrowser, OS, device, country breakdown
GET/api/analytics/realtimeLive visitors
GET/api/analytics/visitorsVisitor list
GET/api/analytics/visitors/:idVisitor detail
GET/api/analytics/sessionsSession list
GET/api/analytics/sessions/:idSession detail
GET/api/goalsList goals
POST/api/goalsCreate goal
GET/api/goals/:idGoal detail + conversions
DELETE/api/goals/:idDelete goal
GET/api/exportExport data (JSON or CSV)

All analytics endpoints accept siteId, period, and timezone query parameters. Authenticate with a Bearer token or session cookie.

Export

Export raw data for external analysis.

GET/api/export
siteIdstringrequired
Your site ID
typestring
pageviews (default), events, sessions, visitors
formatstring
json (default) or csv
periodstring
Time range (default: 7d)
terminal
# Export last 30 days of sessions as CSV
curl -H "Authorization: Bearer $TOKEN" \
  "https://srcbeam.com/api/export?siteId=abc123&type=sessions&format=csv&period=30d"