SDK advanced patterns: replay, exports and webhooks
Replay recordings, verify webhooks, respect billing limits, and share expiring replay links with the Synento SDK.
The examples are ES modules (save them as .mjs) and read your key from
SYNENTO_API_KEY. SYNENTO_API_URL is only needed against a server other than
https://api.synento.com.
Pattern 1: Session replay engine with auto-looping
Reads a recording back window by window through the playback API. Every window you read counts toward your plan's replay-minute allowance, the same as a viewer watching it.
import { createSynentoClient } from "@synento/node";
const API_URL = process.env.SYNENTO_API_URL ?? "https://api.synento.com";
const API_KEY = process.env.SYNENTO_API_KEY;
const synento = createSynentoClient({ apiKey: API_KEY, baseUrl: API_URL });
/**
* Replay a session by streaming its recorded events through the playback API.
*/
async function replaySession(sessionId, onVideoFrame) {
// Fetch the manifest for the participant list and time bounds
const manifest = await synento.getSessionManifest(sessionId);
if (manifest.start_ts === null) {
console.log("Nothing has been recorded in this session yet");
return;
}
console.log(`Session has ${manifest.participants.length} participants, ` +
`capabilities: ${manifest.capabilities.join(", ")}`);
// Walk through the session window by window (timestamps are Unix ms)
let fromTs = manifest.start_ts;
const windowSize = 30_000; // 30 seconds per window
let eventCount = 0;
while (fromTs <= manifest.end_ts) {
const windowUrl = `${API_URL}/v1/sessions/${sessionId}/playback?from_ts=${fromTs}&window_size=${windowSize}`;
const windowRes = await fetch(windowUrl, {
headers: { Authorization: `Bearer ${API_KEY}` },
});
if (!windowRes.ok) throw new Error(`playback failed: HTTP ${windowRes.status}`);
const { data } = await windowRes.json();
for (const event of data.events) {
const streamId = event.stream_id;
if (streamId.includes("/media/") && streamId.endsWith("/cam")) {
const userId = streamId.split("/media/")[1]?.split("/")[0];
const buf = Buffer.from(event.body_base64, "base64");
await onVideoFrame(buf, userId, event.timestamp);
} else if (streamId.endsWith("/events") || streamId.endsWith("/director")) {
// Timeline events — useful for layout/state reduction
} else if (streamId.endsWith("/chat")) {
const msg = JSON.parse(Buffer.from(event.body_base64, "base64").toString());
console.log(`[chat] ${msg.user_id}: ${msg.text}`);
}
eventCount++;
if (eventCount % 100 === 0) {
console.log(`Replayed ${eventCount} events...`);
}
}
// A quiet stretch returns an empty window; keep going until end_ts
fromTs += windowSize;
}
console.log(`Replay complete: ${eventCount} total events`);
}
// Usage: count camera frames per participant
const framesPerUser = new Map();
await replaySession("YOUR_SESSION_ID", async (frame, userId) => {
// `frame` is one encoded video frame in Synento's EVC1 container, not an
// image: decode it with WebCodecs (see parseEvcPayload in @synento/client)
// or export the session to MP4 if you need pictures.
framesPerUser.set(userId, (framesPerUser.get(userId) ?? 0) + 1);
});
console.log(framesPerUser);Pattern 2: Webhook handler with signature verification
The signature (X-Synento-Signature-V2: t=<unix seconds>,v1=<hex>) is an
HMAC-SHA256 of <t>. followed by the raw request body, so the route must
receive the bytes exactly as sent. Use express.raw, not express.json.
Re-serialising parsed JSON produces different bytes and never verifies.
import { createHmac, timingSafeEqual } from "node:crypto";
const API_URL = process.env.SYNENTO_API_URL ?? "https://api.synento.com";
const API_KEY = process.env.SYNENTO_API_KEY;
// Returned once, when the webhook is created (POST /v1/webhooks)
const WEBHOOK_SECRET = process.env.SYNENTO_WEBHOOK_SECRET;
function verifyWebhookSignature(rawBody, header) {
const { t, v1 = "" } = Object.fromEntries(header.split(",").map((p) => p.split("=")));
// Refuse anything signed more than 5 minutes ago, so a captured delivery
// cannot be replayed later.
if (!t || Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
// Lowercase hex HMAC-SHA256 over "<t>." + the raw body bytes, exactly as received
const expected = createHmac("sha256", WEBHOOK_SECRET)
.update(`${t}.`)
.update(rawBody)
.digest("hex");
// Constant-time comparison to prevent timing attacks
return (
v1.length === expected.length &&
timingSafeEqual(Buffer.from(v1), Buffer.from(expected))
);
}
/**
* Example Express handler for processing webhooks. Mount it with the raw
* body parser:
*
* app.post("/webhooks/synento", express.raw({ type: "application/json" }), webhookHandler);
*/
export function webhookHandler(req, res) {
const signature = req.headers["x-synento-signature-v2"];
if (!signature) {
return res.status(401).json({ error: "Missing signature" });
}
if (!verifyWebhookSignature(req.body, signature)) {
console.warn("Invalid webhook signature from", req.ip);
return res.status(403).json({ error: "Invalid signature" });
}
// Payload: { id, type, project_id, session_id, data }
const payload = JSON.parse(req.body.toString("utf8"));
// Process asynchronously — respond immediately. Answer 200 even for event
// types you ignore: any non-2xx response is treated as a failed delivery
// and retried.
processWebhookEvent(payload).catch(err => {
console.error(`Failed to process webhook ${payload.type}:`, err);
});
res.status(200).send("OK");
}
async function processWebhookEvent(payload) {
switch (payload.type) {
case "session.started":
// Session just went live — notify participants, start recording analytics...
console.log(`🟢 LIVE: ${payload.session_id} started`);
break;
case "session.ended":
// Session ended — trigger export, send email notifications...
console.log(`⏹️ ENDED: ${payload.session_id}`);
// Optionally trigger MP4 export (each export counts toward your plan's
// export allowance, then is billed on pay-as-you-go; repeating it is free)
await triggerExport(payload.session_id);
break;
case "export.completed":
// An MP4 for this session is ready. The payload carries the session id,
// not the job id — keep the job id from when you started the export.
console.log(`📦 EXPORTED: ${payload.session_id}`);
break;
case "transcript.ready":
// The transcript is finished: read it with getTranscript(session_id).
// data.languages lists the languages it holds.
console.log(`📝 TRANSCRIBED: ${payload.session_id}`, payload.data.languages);
break;
default:
console.log(`Event: ${payload.type} for session ${payload.session_id}`);
}
}
async function triggerExport(sessionId, opts = {}) {
const params = new URLSearchParams();
if (opts.layout) params.set("layout", opts.layout); // "grid" | "presenter"
if (opts.orientation) params.set("orientation", opts.orientation); // "landscape" | "vertical"
if (opts.focus) params.set("focus", opts.focus); // a participant's user id
const headers = { Authorization: `Bearer ${API_KEY}` };
const exportRes = await fetch(
`${API_URL}/v1/sessions/${sessionId}/export?${params}`,
{ headers }
);
if (!exportRes.ok) {
console.error(`Export enqueue failed for ${sessionId}: HTTP ${exportRes.status}`);
return;
}
const { data: { job_id } } = await exportRes.json();
// Poll until complete
while (true) {
const statusRes = await fetch(`${API_URL}/v1/exports/${job_id}`, { headers });
const { data } = await statusRes.json();
if (data.status === "completed") {
const downloadRes = await fetch(`${API_URL}${data.download_url}`, { headers });
return Buffer.from(await downloadRes.arrayBuffer());
}
if (data.status === "failed") {
throw new Error(data.error ?? "Export failed");
}
await new Promise(r => setTimeout(r, 2000));
}
}Pattern 3: Session queue for production limits
When creating sessions in a loop (e.g. scheduling daily standups), respect billing limits:
import { createSynentoClient, SynentoError } from "@synento/node";
const synento = createSynentoClient({ apiKey: process.env.SYNENTO_API_KEY });
/**
* Create sessions safely, respecting billing limits.
*/
async function createSessionWithLimits(name) {
// Check if we're within limits before attempting creation
const limits = await synento.getBillingLimits();
if (limits.isBlocked) {
throw new Error(`Session creation blocked: ${limits.statusMessage}`);
}
// Safe to create a session — within plan limits
return await synento.createSession({ name });
}
/**
* Process a queue of pending sessions, respecting rate limits.
*/
async function processSessionQueue(pendingSessions) {
const created = [];
for (const name of pendingSessions) {
try {
const session = await createSessionWithLimits(name);
created.push(session);
// Brief delay between sessions to avoid rate limiting
await new Promise(r => setTimeout(r, 500));
} catch (err) {
console.error(`Failed to create "${name}": ${err.message}`);
// If billing limits hit, stop the queue. The API answers 503 when the
// plan's usage limits block new sessions.
if (err.message.startsWith("Session creation blocked") ||
(err instanceof SynentoError && err.status === 503)) {
console.log(`Queue stopped — billing limits exceeded. ${created.length} created.`);
break;
}
// Other errors — continue with next session in queue
}
}
return created;
}Pattern 4: Expiring replay links
Share a private session's recording for a limited time, without making the
session public. The link token grants read access to the recording's playback
data through GET /v1/public/sessions/{id}/replay, with no API key.
import { createSynentoClient } from "@synento/node";
const API_URL = process.env.SYNENTO_API_URL ?? "https://api.synento.com";
const synento = createSynentoClient({ apiKey: process.env.SYNENTO_API_KEY });
async function createShareLink(sessionId, ttlMinutes = 1440) { // default: 24 hours
// ttlMinutes: 1 to 43200 (30 days)
const { token } = await synento.createReplayLink(sessionId, ttlMinutes);
// Playback windows start at an absolute Unix-ms timestamp, so hand the
// viewer the session's start rather than 0.
const { start_ts } = await synento.getSessionManifest(sessionId);
return `${API_URL}/v1/public/sessions/${sessionId}/replay` +
`?token=${token}&from_ts=${start_ts ?? 0}&window_size=15000`;
}
const url = await createShareLink("YOUR_SESSION_ID", 43200); // max: 30 daysThe URL returns one playback window as JSON, the same shape as
GET /v1/sessions/{id}/playback, with base64-encoded frames, not a web page,
so it cannot be dropped into an <iframe>. Your viewer page fetches it and
renders the frames, advancing from_ts by window_size for each next window.
Reads through a link count toward your replay-minute allowance, and the link
stops working when it expires.