Codex LaboratoriesAnalytics
Sign inGet started

Developer Documentation

Everything needed to install the beacon, ingest events, query analytics, and operate the platform - verified against the running system.

Quick start

  1. Register - create an account; you become the admin of a new organization.
  2. Add a property - the dashboard issues a tracking ID (trk_…) per site.
  3. 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

GlobalDefaultPurpose
ANALYTICS_TRACKING_IDrequiredYour property's tracking ID.
ANALYTICS_API_ENDPOINT/api/eventsOverride the ingest endpoint (self-hosted proxies).

What it captures

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

ResponseMeaning
{"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 CORSOrigin not in the ingest allowlist (ALLOWED_ORIGINS).
400/429Contract 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.

EndpointMin roleReturns
GET /api/websitesviewerYour properties + counts, ingest freshness, uptime state, your role on each.
POST /api/websitesanyCreate property → issues tracking ID.
GET/PATCH/DELETE /api/websites/[id]viewer/admin/ownerProperty detail, settings update, cascade delete.
GET/POST /api/websites/[id]/accessadminList grants; grant/revoke member roles.
GET /api/websites/[id]/audit?days=adminAudit ledger for that property.
POST /api/websites/[id]/rotate-trackingownerRotate tracking ID (old ID stops ingesting).
GET /api/analytics?websiteId=&startDate=&endDate=viewerMetrics + deltas, top pages, sources, devices, browsers, daily pageviews.
GET /api/analytics/geographic?websiteId=viewerCountry/city session breakdowns (bots excluded).
GET /api/analytics/realtime?websiteId=viewerActive visitors, last-hour counts (also pushed over Socket.IO).
GET /api/analytics/explore?websiteId=&dataset=&page=analystBounded record queries: pageviews|sessions|events. ≤93d window, ≤100/page.
GET /api/analytics/cohorts?websiteId=&weeks=analystWeekly first-seen cohort retention matrix (≤26 weeks).
GET /api/analytics/anomalies?websiteId=&days=analystModified z-score anomaly flags per metric + method/limitations.
GET /api/analytics/quality?websiteId=viewerData-quality checks with stated thresholds.
GET /api/analytics/export?websiteId=&format=csv|jsonanalystRange export; CSV cells are formula-injection escaped.
GET/POST/PATCH /api/funnels, /api/goals, /api/alerts, /api/campaignsviewer/adminFunnel definitions, goals, alert rules, campaign tags.
GET /api/uptime + POST /api/uptimeviewer/adminProbe history; register monitor targets (SSRF-guarded).
GET /api/errorsviewerClient-side error stream.
GET /api/system/statusany signed-inService health, per-site freshness/uptime, jobs ledger tail.
POST /api/assistantany signed-inGrounded AI assistant: injects verified metrics for a websiteId you can access.

Custom boards API

EndpointMin rolePurpose
GET /api/dashboards?websiteId=viewerList boards for the property.
POST /api/dashboardsanalystCreate board (≤25 per property).
GET/PATCH/DELETE /api/dashboards/[id]viewer/analystLoad, rename/re-range/replace widgets atomically, delete.
POST /api/dashboards/[id]/duplicateanalystCopy 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

EndpointAccessPurpose
GET/POST /api/support/ticketsowner; staff ?all=1Your tickets / open a ticket (dedup on subject+window).
GET/PATCH /api/support/tickets/[id]owner or staffThread (internal notes stripped for customers); status/priority/assignee.
POST /api/support/tickets/[id]/replyowner or staffAppend message; staff can post internal notes.
POST /api/support/tickets/[id]/attachmentsowner or staffMultipart upload, ≤5 MB, magic-byte type validation.
GET /api/support/attachments/[id]owner or staffAuthenticated download.
GET /api/support/statsstaffBacklog, SLO breaches, avg response/resolution.
POST /api/support-chatanon 5/min · user 20/minAsk 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.

PlanSitesEvents/moRetention
Free110,00030 days
Pro - $9/mo or $90/yr10500,00012 months
Business - $29/mo or $290/yrUnlimited5,000,000Unlimited

Endpoints

EndpointAccessPurpose
GET /api/billingauthenticatedThe caller's plan and subscription state (used by /pricing to mark the current plan).
POST /api/billing/checkoutauthenticatedCreates 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/apexAPEX-signedX-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

RoleCan do
viewerRead dashboards, realtime, uptime, errors, funnels, campaigns, boards, data quality.
analystviewer + exports, explorer, cohorts, anomalies, board create/edit.
editoranalyst + configuration surfaces.
admineditor + goals, alerts, member grants (below owner), audit log, settings.
owneradmin + 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

Data pipeline & scheduled jobs

Troubleshooting

SymptomLikely cause → fix
Beacon loads, no eventsCORS: 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 foreverOnly monitor visits are arriving. Real traffic flips it to live.
CSP blocks the beaconAllow script-src https://analytics.codexlabsai.com and connect-src https://analytics.codexlabsai.com.
Explorer/cohorts 403Those 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 emptyNeeds ≥14 days of rollup history; small sites legitimately produce few flags.
Attachment upload 400Magic-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).