Developer Documentation
Everything needed to install the beacon, ingest events, query analytics, and operate the platform - verified against the running system.
Quick start
- Register - create an account; you become the admin of a new organization.
- Add a property - the dashboard issues a tracking ID (
trk_…) per site. - Install the beacon - paste the snippet before
</body>:
<script>
window.ANALYTICS_TRACKING_ID='trk_YOUR_ID';
</script>
<script src="https://analytics.codexlabsai.com/analytics.js" defer></script>Verify - load the page over its public hostname and watch for a POST /api/events → {"success":true} in DevTools → Network. Localhost and LAN IPs are filtered by design; verify from a public origin.
Tracking beacon (analytics.js)
A ~4 KB first-party script. It generates stable visitor/session IDs, queues events, batches them, uses sendBeacon when available, and records pageviews automatically - including SPA navigation via history interception. No cookies, no third-party calls.
Configuration
| Global | Default | Purpose |
|---|---|---|
| ANALYTICS_TRACKING_ID | required | Your property's tracking ID. |
| ANALYTICS_API_ENDPOINT | /api/events | Override the ingest endpoint (self-hosted proxies). |
What it captures
pageview- every navigation, with URL, title, referrer, UTM parameters.error- uncaught exceptions land in the error stream.- Session duration accumulates as the visitor keeps navigating.
Ingest API - POST /api/events
Public, unauthenticated-by-design endpoint (the tracking ID is the credential). Server-side events are welcome - send the same contract from your backend for conversions or offline events.
Single event
POST /api/events
Content-Type: application/json
{
"trackingId": "trk_YOUR_ID",
"type": "pageview", // pageview | custom | conversion | error
"url": "https://yoursite/path",
"eventId": "evt_unique_1", // dedup key - retries never double-count
"sessionId": "ses_abc",
"visitorId": "vst_xyz",
"title": "Page title",
"referrer": "https://google.com",
"utmSource": "newsletter" // utmSource/Medium/Campaign/Term/Content
}Batch
{ "events": [ {…}, {…}, {…} ] }Custom events & conversions
{ "trackingId": "trk_…", "type": "custom", "name": "signup",
"category": "onboarding", "value": 1, "eventId": "evt_2" }
{ "trackingId": "trk_…", "type": "conversion", "goalId": "signup",
"value": 49.0, "currency": "USD", "eventId": "evt_3" }Response semantics
| Response | Meaning |
|---|---|
| {"success":true} | Accepted (or already-seen eventId - dedup is silent). |
| {"filtered":true,"reason":"internal-traffic"} | Loopback/LAN source IP or a localhost event URL. |
| {"filtered":true,"reason":"tracking-id-excluded"} | Property on the EXCLUDED_TRACKING_IDS blocklist. |
| 403 CORS | Origin not in the ingest allowlist (ALLOWED_ORIGINS). |
| 400/429 | Contract violation or rate limited. |
Bots are classified at ingest (UA + heuristics) and excluded from analytics - they never leave the raw tables, so filtering is reversible per query. IPs are anonymized before storage.
Analytics API (authenticated)
Session-cookie auth on every route. All site-scoped endpoints enforce requireWebsiteAccess server-side - the minimum role is listed per route.
| Endpoint | Min role | Returns |
|---|---|---|
| GET /api/websites | viewer | Your properties + counts, ingest freshness, uptime state, your role on each. |
| POST /api/websites | any | Create property → issues tracking ID. |
| GET/PATCH/DELETE /api/websites/[id] | viewer/admin/owner | Property detail, settings update, cascade delete. |
| GET/POST /api/websites/[id]/access | admin | List grants; grant/revoke member roles. |
| GET /api/websites/[id]/audit?days= | admin | Audit ledger for that property. |
| POST /api/websites/[id]/rotate-tracking | owner | Rotate tracking ID (old ID stops ingesting). |
| GET /api/analytics?websiteId=&startDate=&endDate= | viewer | Metrics + deltas, top pages, sources, devices, browsers, daily pageviews. |
| GET /api/analytics/geographic?websiteId= | viewer | Country/city session breakdowns (bots excluded). |
| GET /api/analytics/realtime?websiteId= | viewer | Active visitors, last-hour counts (also pushed over Socket.IO). |
| GET /api/analytics/explore?websiteId=&dataset=&page= | analyst | Bounded record queries: pageviews|sessions|events. ≤93d window, ≤100/page. |
| GET /api/analytics/cohorts?websiteId=&weeks= | analyst | Weekly first-seen cohort retention matrix (≤26 weeks). |
| GET /api/analytics/anomalies?websiteId=&days= | analyst | Modified z-score anomaly flags per metric + method/limitations. |
| GET /api/analytics/quality?websiteId= | viewer | Data-quality checks with stated thresholds. |
| GET /api/analytics/export?websiteId=&format=csv|json | analyst | Range export; CSV cells are formula-injection escaped. |
| GET/POST/PATCH /api/funnels, /api/goals, /api/alerts, /api/campaigns | viewer/admin | Funnel definitions, goals, alert rules, campaign tags. |
| GET /api/uptime + POST /api/uptime | viewer/admin | Probe history; register monitor targets (SSRF-guarded). |
| GET /api/errors | viewer | Client-side error stream. |
| GET /api/system/status | any signed-in | Service health, per-site freshness/uptime, jobs ledger tail. |
| POST /api/assistant | any signed-in | Grounded AI assistant: injects verified metrics for a websiteId you can access. |
Custom boards API
| Endpoint | Min role | Purpose |
|---|---|---|
| GET /api/dashboards?websiteId= | viewer | List boards for the property. |
| POST /api/dashboards | analyst | Create board (≤25 per property). |
| GET/PATCH/DELETE /api/dashboards/[id] | viewer/analyst | Load, rename/re-range/replace widgets atomically, delete. |
| POST /api/dashboards/[id]/duplicate | analyst | Copy board + widgets. |
Widget types: kpi (metric + delta), line (daily pageviews), bar and table (topPages | trafficSources | deviceBreakdown | browserBreakdown). Layout is a 12-column grid - col 0-11, row 0-49, w 1-12, h 1-6, validated server-side; a board never saves a partial layout.
Support desk API
| Endpoint | Access | Purpose |
|---|---|---|
| GET/POST /api/support/tickets | owner; staff ?all=1 | Your tickets / open a ticket (dedup on subject+window). |
| GET/PATCH /api/support/tickets/[id] | owner or staff | Thread (internal notes stripped for customers); status/priority/assignee. |
| POST /api/support/tickets/[id]/reply | owner or staff | Append message; staff can post internal notes. |
| POST /api/support/tickets/[id]/attachments | owner or staff | Multipart upload, ≤5 MB, magic-byte type validation. |
| GET /api/support/attachments/[id] | owner or staff | Authenticated download. |
| GET /api/support/stats | staff | Backlog, SLO breaches, avg response/resolution. |
| POST /api/support-chat | anon 5/min · user 20/min | Ask Sybil support assistant (server-held keys; 503 when unconfigured). |
Ticket states: OPEN → PENDING → RESOLVED → CLOSED (staff). Customers can only OPEN (reopen) or CLOSE their own tickets. Other users' tickets return a uniform 404 - existence is never revealed.
Billing & plans
Plans resolve from a server-side catalog (PLAN_DEFINITIONS) - prices and limits are never taken from the client. An organization with no active Subscription row is on the Free plan. The tracked-sites limit is enforced in POST /api/websites (403 PLAN_LIMIT); existing sites are never removed by a downgrade. Event volume is a fair-use allowance - see /pricing.
| Plan | Sites | Events/mo | Retention |
|---|---|---|---|
| Free | 1 | 10,000 | 30 days |
| Pro - $9/mo or $90/yr | 10 | 500,000 | 12 months |
| Business - $29/mo or $290/yr | Unlimited | 5,000,000 | Unlimited |
Endpoints
| Endpoint | Access | Purpose |
|---|---|---|
| GET /api/billing | authenticated | The caller's plan and subscription state (used by /pricing to mark the current plan). |
| POST /api/billing/checkout | authenticated | Creates an APEX hosted checkout session for {planKey, interval}; server resolves the amount. 503 APEX_DISABLED until checkout is enabled; 409 if already subscribed. |
| POST /api/webhooks/apex | APEX-signed | X-Apex-Signature HMAC (300s tolerance); idempotent on event id via the PaymentEvent ledger. payment.captured re-fetches authoritative state then activates the subscription; payment.refunded cancels it. |
Card details never touch this site - checkout is hosted by APEX (payments.codexlabsai.com). Operators: set APEX_API_KEY + APEX_WEBHOOK_SECRET, then APEX_CHECKOUT_ENABLED=1 to show self-serve upgrade buttons. Webhook processing stays on regardless so refunds and failures always land.
Roles & permissions
| Role | Can do |
|---|---|
| viewer | Read dashboards, realtime, uptime, errors, funnels, campaigns, boards, data quality. |
| analyst | viewer + exports, explorer, cohorts, anomalies, board create/edit. |
| editor | analyst + configuration surfaces. |
| admin | editor + goals, alerts, member grants (below owner), audit log, settings. |
| owner | admin + owner grants, tracking-ID rotation, delete site. |
Role floors are enforced server-side on every route - the UI hides what you can't do, but the API is the real boundary. Support-desk staff are a separate axis: the SUPPORT_STAFF_EMAILS env allowlist, not a per-site role.
Metric definitions
- Pageviews - pageview events from non-bot sessions in the window.
- Sessions - distinct sessions attributed to real visitors.
- Unique visitors - distinct visitor IDs across real sessions.
- Bounce rate - share of real sessions with exactly one pageview.
- Deltas - arithmetic comparison vs. the immediately preceding equal-length period. Not a forecast.
- Cohort retention - a visitor's cohort is the ISO week of their first session; retention Wn is the share of that cohort with ≥1 session n weeks later. Computed over real sessions, not modeled.
- Anomaly flag - a daily rollup value flagged when its modified z-score (0.6745·(x−median)/MAD) reaches |z| ≥ 3.5. An outlier, not a diagnosis - no day-of-week seasonality is modeled.
- Data-quality checks - per-property diagnostics (freshness, bot share, geo/device coverage, session linking, uptime) with fixed, stated thresholds. Check before trusting affected metrics.
- Freshness badges -
live= human traffic recently;synth= monitor traffic only;stale= no ingest in 24h;none= never ingested.
Data pipeline & scheduled jobs
- Ingest → events queue through a serialized write path into SQLite (Prisma), with eventId dedup and bot classification.
- rollup-daily → aggregates each day into
DailyMetric(the anomaly detector's baseline). - freshness-check → marks properties STALE when ingest goes quiet.
- alert-worker → evaluates threshold/freshness alert rules on a schedule.
- uptime-worker → probes monitor targets; 401/403/405 can be allowlisted per-site as "auth-gated".
- purge-old-data → retention cleanup (dry-run by default).
- synthetic-visit → real-browser visits every 30 min keep the ingest path proven; classified separately from human traffic.
- monitor-watchdog → supervises the job set; the ledger lands in
logs/jobs.jsonl→ Status & Jobs.
Troubleshooting
| Symptom | Likely cause → fix |
|---|---|
| Beacon loads, no events | CORS: origin not in the ingest allowlist → ask an operator to add it; or you're testing from localhost/LAN - internal IPs are filtered by design. |
{"filtered":true} | Read the reason: tracking-id-excluded = blocklisted property; internal-traffic = private source IP or localhost event URL. |
data: synth forever | Only monitor visits are arriving. Real traffic flips it to live. |
| CSP blocks the beacon | Allow script-src https://analytics.codexlabsai.com and connect-src https://analytics.codexlabsai.com. |
| Explorer/cohorts 403 | Those endpoints need analyst role or above - ask a site admin to upgrade your grant. |
| Assistant says "not configured" | Ask Sybil keys are unset on this deployment - use the ticket desk instead. |
| Anomalies panel empty | Needs ≥14 days of rollup history; small sites legitimately produce few flags. |
| Attachment upload 400 | Magic-byte check failed - file content must be a real image/PDF/zip/text under 5 MB. |
Still stuck? Open a support ticket or ask the assistant (chat bubble, bottom right).