Documentation
Everything you need to integrate SourceBeam with AI agents, CLI tools, and custom applications.
Quick start
Get reliable analytics data in 4 steps:
- Install the tracking script on every route you want counted.
- Verify that SourceBeam sees your first real pageview on the deployed site.
- Optionally connect Stripe for revenue sync and attribution.
- Generate an API read token in Site Settings and call the API.
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:
<script defer src="https://srcbeam.com/sb.js" data-site="YOUR_SITE_ID"></script>
Next.js App Router install:
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.
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.
/api/aiWithout siteId, returns a full markdown instruction file for AI agents — self-documenting API.
Parameters
siteIdstringrequiredsectionsstringsummary, overview, chart, pages, sources, devices, realtime, visitors, sessions, goals. Omit for all.periodstringtoday, 24h, 7d (default), 30d, 90d, 12m, alltimezonestringEurope/Warsawlimitnumberoffsetnumbercurl -H "Authorization: Bearer $TOKEN" \ "https://srcbeam.com/api/ai?siteId=abc123§ions=overview,pages&period=30d"
{
"_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:
{
"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:
{
"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
claude mcp add sourcebeam -- npx tsx /path/to/sourcebeam/mcp/server.ts
Available tools
| Tool | Description |
|---|---|
list_sites | List all your sites |
get_analytics | Fetch any analytics section |
get_realtime | Live visitor count + active pages |
compare_periods | Current vs previous period metrics |
get_visitor | Full visitor history and conversions |
get_session | Full session event timeline |
create_goal | Create a conversion goal |
export_data | Export raw data as JSON |
CLI
Query analytics from the terminal. The CLI calls the /api/ai endpoint and formats the output for the 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
| Command | Description |
|---|---|
summary | Natural-language analytics summary |
overview | Key metrics (visitors, sessions, bounce rate, revenue) |
pages | Top pages by views |
sources | Traffic sources (referrers, UTM, direct) |
devices | Countries, browsers, OS, device types |
realtime | Currently active visitors |
sessions | Recent session list |
goals | Conversion goals |
all | Everything at once |
Options
--periodstringtoday, 24h, 7d (default), 30d, 90d, 12m, all--sitestringSRCBEAM_SITE env var)--jsonflagWhich 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
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:
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:
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
sbMetato the backend unchanged. - The paid Stripe flow still carries
sb_visitorandsb_session. - Existing auth, return URLs, pricing, and billing behavior remain unchanged.
Payment Intent
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
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
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 ElementsMetadata 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
sbMetawithout changing the rest of the payload. - The Stripe object SourceBeam sync reads still exposes
sb_visitorandsb_session. - No confirmation, webhook, or capture logic regresses.
Payment Links
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.
- Go to your Stripe Payment Link settings
- Open the After payment tab
- 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.jsand 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.
# 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.
| Method | Path | Description |
|---|---|---|
| GET | /api/analytics/overview | Key metrics + chart + previous period |
| GET | /api/analytics/pages | Top pages |
| GET | /api/analytics/sources | Traffic sources |
| GET | /api/analytics/devices | Browser, OS, device, country breakdown |
| GET | /api/analytics/realtime | Live visitors |
| GET | /api/analytics/visitors | Visitor list |
| GET | /api/analytics/visitors/:id | Visitor detail |
| GET | /api/analytics/sessions | Session list |
| GET | /api/analytics/sessions/:id | Session detail |
| GET | /api/goals | List goals |
| POST | /api/goals | Create goal |
| GET | /api/goals/:id | Goal detail + conversions |
| DELETE | /api/goals/:id | Delete goal |
| GET | /api/export | Export 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.
/api/exportsiteIdstringrequiredtypestringpageviews (default), events, sessions, visitorsformatstringjson (default) or csvperiodstring7d)# 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"