Spectra Logo SPECTRA DOCS
Docs / Developer Reference / Spectra Platform Architecture

Spectra Developer Documentation

Spectra provides lightweight, deterministic session replay and friction telemetry. The client recorder operates asynchronously off the main thread, capping bandwidth with strict byte budgets while guaranteeing zero impact on Core Web Vitals.

60-Second Quickstart

Embed the single asynchronous script snippet into the head of your web application. The recorder initializes immediately and queues commands automatically before network bundle arrival.

HTML / Universal Snippet
<script src="https://app.spectra.dev/sdk/spectra.min.js"></script> <script> Spectra.record({ apiKey: 'sp_live_xxxxxxxx', siteId: 'site_xxxxxxxx', endpoint: 'https://app.spectra.dev/v1/ingest' }); </script>
Async Load Queue: For Google Tag Manager or custom script loaders, commands can be pushed to window.spectraQ prior to script execution without risking execution order errors.

Verifying Installation

Confirm telemetry transport directly from your browser developer tools console. Run the following command on any page where the SDK is embedded:

Browser Console Verification
Spectra.current().flag('test_install');

The Spectra Sessions dashboard updates within seconds displaying a test_install trigger tag alongside your current session replay.

Buffer and Evidence Recording Model

Traditional session replay tools continuously stream video data over WebSocket connections, accumulating massive storage overhead for idle visitors. Spectra uses a dual-state architecture:

Component Mechanism Network Overhead
Silent RAM Buffer Keeps a 30-second rolling ring buffer of DOM mutations and console events in client memory. 0 KB / sec transmitted
Evidence Capture Flushes the 30-second pre-crash lead-up plus 10-second resolution tail only when friction occurs. Fixed plan quota (default 50KB)
Degradation Pulse Transmits 200-byte aggregate interaction metrics to monitor conversion rate anomalies. ~0.2 KB per session

Ad-Blocker Bypass and First-Party Tunneling

Ad-blockers such as uBlock Origin, AdBlock Plus, and privacy protections like Brave Shields or Safari ITP frequently block network calls to third-party domains. Spectra features native First-Party SDK Tunneling, routing telemetry through your own domain so ad-blockers cannot inspect or drop requests.

SDK Tunnel Configuration
import { record } from '@spectra/recorder'; record({ apiKey: 'sp_live_xxxxxxxx', siteId: 'site_xxxxxxxx', tunnel: '/api/spectra-tunnel' // Same-origin endpoint });

Next.js (App Router Route Handler)

Create an API route handler under app/api/spectra-tunnel/route.ts:

app/api/spectra-tunnel/route.ts
import { NextResponse } from 'next/server'; export async function POST(req: Request) { const url = new URL(req.url); const target = url.searchParams.get('target') || 'ingest'; const targetUrl = `https://ingest.spectra.dev/v1/${target}${url.search}`; const res = await fetch(targetUrl, { method: 'POST', body: await req.arrayBuffer(), headers: { 'Content-Type': req.headers.get('Content-Type') || 'text/plain' }, }); return new NextResponse(res.body, { status: res.status }); } export async function GET(req: Request) { const url = new URL(req.url); const targetUrl = `https://ingest.spectra.dev/v1/config${url.search}`; const res = await fetch(targetUrl); return new NextResponse(res.body, { status: res.status }); }

Express.js / Node.js Backend Middleware

Express Middleware
app.use('/api/spectra-tunnel', express.raw({ type: '*/*' }), async (req, res) => { const target = req.query.target || (req.method === 'GET' ? 'config' : 'ingest'); const query = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : ''; const targetUrl = `https://ingest.spectra.dev/v1/${target}${query}`; const response = await fetch(targetUrl, { method: req.method, headers: { 'Content-Type': req.headers['content-type'] || 'text/plain' }, body: req.method === 'POST' ? req.body : undefined, }); res.status(response.status).send(Buffer.from(await response.arrayBuffer())); });

Zero-Backend Host Rewrites (Vercel & Netlify)

For static client single page applications without a custom backend server, configure edge redirects at your CDN proxy:

vercel.json Rewrites
{ "rewrites": [ { "source": "/api/spectra-tunnel/:path*", "destination": "https://ingest.spectra.dev/v1/:path*" } ] }

Trigger Engine and Smart Session Sampling

Spectra does not waste byte bandwidth recording peaceful, uneventful user sessions. Telemetry uploads occur strictly when diagnostic triggers fire.

Automatic Default Triggers

Trigger Signal Detection Condition Reason Label
Uncaught Exception Unhandled JavaScript errors or unhandled promise rejections. uncaught_error
Console Error console.error() invocations with stack traces. console_error
Network Failure HTTP requests returning 4xx or 5xx response status codes. network_error
Rage Click Repeated clicks (>3 within 900ms) on a static or un-interactive element. rage_click
Struggle Loop Repeated input clearing, form validation thrashing, or abandon after effort. struggle

Programmatic Code Triggers

Dispatch custom business events or update session properties dynamically from your application logic:

SDK Event Signals
const spectra = Spectra.record({ apiKey, siteId, endpoint }); // 1. Emit business event for rule evaluation spectra.track('PaymentFailed', { gateway: 'stripe', errorCode: 'card_declined' }); // 2. Set session metadata properties spectra.setProps({ userPlan: 'enterprise', cartValue: 499 }); // 3. Force-record session immediately with custom reason label spectra.flag('vip_checkout_stuck');

Zero-JS HTML Markup Triggers

Annotate HTML elements directly to capture friction points without custom script logic:

HTML Trigger Attributes
<button data-spectra-trigger="checkout_submit_clicked">Complete Purchase</button> <div data-spectra-flag="card_authorization_failed">Your card was declined</div>

Dashboard Trigger Rule Conditions

Configure dynamic trigger rules in the Spectra Dashboard (Sites → Trigger Rules). Rules propagate instantly to client SDKs without requiring code redeployments:

Trigger Rule JSON Schema
[ { "id": "high-value-payment-failed", "on": { "event": "PaymentFailed" }, "where": [{ "key": "cartValue", "op": "gte", "value": 300 }], "reason": "high_value_payment_failed", "sampleRate": 1.0, "kind": "issue" } ]
Operator (op) Description
eq / neq Equals / Not equals target value.
gt / gte Greater than / Greater than or equal to numeric threshold.
lt / lte Less than / Less than or equal to numeric threshold.
contains String substring matching.
exists Property key presence check.

Framework Integration Reference

React and Next.js (App Router)

Install the official package from npm:

Terminal
npm install @spectra/recorder
components/SpectraProvider.tsx
'use client'; import { useEffect } from 'react'; import { record } from '@spectra/recorder'; export function SpectraProvider() { useEffect(() => { const instance = record({ apiKey: process.env.NEXT_PUBLIC_SPECTRA_KEY!, siteId: process.env.NEXT_PUBLIC_SPECTRA_SITE_ID!, endpoint: 'https://app.spectra.dev/v1/ingest', }); return () => instance.stop(); }, []); return null; }

Vue 3 and Nuxt 3

Create a client plugin inside your Nuxt project under plugins/spectra.client.ts:

plugins/spectra.client.ts
import { record } from '@spectra/recorder'; export default defineNuxtPlugin(() => { record({ apiKey: 'sp_live_xxxxxxxx', siteId: 'site_xxxxxxxx', endpoint: 'https://app.spectra.dev/v1/ingest', }); });

SDK Configuration Parameters

The record() initialization method accepts an object with the following parameters:

Parameter Type Default Description
apiKey string Required Public project API key generated from the Spectra dashboard.
siteId string Required Unique site identifier linking recorded sessions to your organization workspace.
endpoint string Required Target ingestion server HTTP URL (/v1/ingest).
tunnel string null Same-origin proxy path for first-party ad-blocker bypass.
userId string null Internal user identification string for cross-session correlation.
privacyMode string 'default' Set to 'strict' to redact all plain text content across the document tree.
maskInputs boolean true Automatically masks input element values before recording.

User Identity and Event Tracking

Link incoming replay recordings to your internal user accounts using identify():

User Identification
const spectra = Spectra.record({ apiKey, siteId, endpoint }); // Call after user login completes spectra.identify('user_94821');

On-Device Privacy and PII Masking

Spectra redacts sensitive information client-side prior to network dispatch. Passwords, credit card numbers, and auth tokens are stripped at the DOM serialization layer.

HTML Attribute Behavior
data-spectra-mask Replaces text contents and form field values with asterisks.
data-spectra-block Completely hides the element and all child nodes, replacing it with a placeholder box.
data-spectra-unmask Overrides global strict masking for public, non-sensitive content elements.

GDPR User Erasure API

Execute programmatic data deletion requests using the server REST endpoint:

cURL / REST Request
curl -X DELETE "https://app.spectra.dev/v1/user-data?site=site_xxxxxxxx&user=user_94821" \ -H "Authorization: Bearer YOUR_ADMIN_TOKEN"