Web quickstart: live video in a web page
Join a live Synento session from the browser with two-way audio and video, using a short-lived connection token minted by your server.
Join a live Synento session from the browser with two-way audio and video. It
takes two pieces: a small server route that mints a short-lived connection
token, and a page that uses @synento/client to publish and receive media.
Never put your API key in the browser
Your sk_live_… key can create sessions, read recordings, and change billing.
It must stay on your server. The browser only ever receives a connection
token: a short-lived credential scoped to one session and one user.
browser ──POST /api/connection──▶ your server ──sk_live_…──▶ Synento API
◀── { wsUrl, token } ──────────────────────────────────────────┘1. Install
npm install @synento/client # browser
npm install @synento/node # your server2. Mint a token on your server
This example is a Next.js route handler; any server framework works the same way. Create the session once (or look up an existing one), then mint a token for the user who is joining.
// app/api/connection/route.ts
import { createSynentoClient, resolveWsUrl } from '@synento/node'
// Reads SYNENTO_API_KEY and SYNENTO_API_URL from the environment.
const synento = createSynentoClient({})
// Without this, Next may statically optimise the route and serve a stale token.
export const dynamic = 'force-dynamic'
export async function POST(request: Request) {
const { sessionId, userId } = await request.json()
// Authenticate the caller here — whoever gets a token can join this session.
const token = await synento.createConnectionToken(sessionId, { userId })
return Response.json({
expiresIn: token.expiresIn,
token: token.accessToken,
// Let the SDK build this. Assembling the URL by hand works in production
// and then fails on localhost, because the browser and the API commonly
// disagree about how to spell loopback — and the rejection arrives as a
// close(1008) *after* a successful upgrade, so it surfaces as a call that
// silently never connects rather than as an error.
wsUrl: resolveWsUrl({
apiBaseUrl: process.env.SYNENTO_API_URL ?? 'https://api.synento.com',
requestOrigin: request.headers.get('origin'),
sessionId,
userId,
}),
})
}3. Join from the browser
SynentoRoom handles encoding, transport, decoding, backpressure, and
reconnection. getToken is a function: the SDK calls it again on
every reconnect, so tokens rotate without any work from you. If getToken
itself throws during a reconnect, the room emits error and stops retrying;
call room.connect() again to resume.
The page needs a <video id="preview" autoplay muted playsinline> element for
your own camera preview.
import { SynentoRoom } from '@synento/client'
const support = SynentoRoom.checkSupport()
if (!support.supported) {
throw new Error(support.reason) // e.g. this browser lacks WebCodecs
}
const userId = 'alice'
const sessionId = 'YOUR_SESSION_ID'
const room = new SynentoRoom({
userId,
getToken: async () => {
const res = await fetch('/api/connection', {
body: JSON.stringify({ sessionId, userId }),
headers: { 'Content-Type': 'application/json' },
method: 'POST',
})
if (!res.ok) throw new Error('could not mint a connection token')
return res.json() // { wsUrl, token }
},
})
// Render each remote participant into a canvas you provide.
room.on('participantsChanged', (participants) => {
for (const id of participants) {
if (document.querySelector(`canvas[data-user="${id}"]`)) continue
const canvas = document.createElement('canvas')
canvas.width = 640
canvas.height = 480
canvas.dataset.user = id
document.body.append(canvas)
room.attachParticipant(id, canvas)
}
})
// Call from your Join click handler, before any await: browsers only start
// sound inside a tap (Safari on iPhone strictly). On 'blocked', show a button
// that calls room.unlockAudio() again.
void room.unlockAudio()
room.on('audioStateChanged', (state) => console.log('sound:', state))
// Whether your own mic reaches the call; 'blocked' is fixed the same way.
room.on('micStateChanged', (state) => console.log('mic:', state))
await room.connect()
// Publish camera and microphone. The <video> element is your local preview.
const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true })
const preview = document.querySelector<HTMLVideoElement>('#preview')!
preview.srcObject = stream
await room.publishCamera(stream, preview)The camera is sent the way it sees you, so others (and the recording) see text the right way round. People expect their own preview mirrored, like a mirror; that is a style on your element and does not change what is sent:
#preview { transform: scaleX(-1); }Open the page in two browser tabs with different user ids and you will see and hear both participants.
Other things you can do
room.setCameraEnabled(false) // mute video, keep audio flowing
room.setMicrophoneEnabled(false) // mute audio; nothing is sent while muted
await room.publishScreen() // share the screen (prompts the user)
room.unpublishScreen()
room.sendChat('hello everyone') // chat is persisted with the recording
room.on('chat', (senderId, message) => console.log(senderId, message.message))
room.close() // leave and release devicesThe chat event fires on the sender too. The server broadcasts the stored
record to everyone in the session, so senderId is your own user id for your
own messages. Render from the event alone; appending the text locally when you
call sendChat shows your messages twice.
Connection state is observable. Use these events for a status indicator:
room.on('connected', () => setStatus('Connected'))
room.on('reconnecting', (attempt) => setStatus(`Reconnecting (${attempt})…`))
room.on('disconnected', (reason) => setStatus(`Disconnected: ${reason}`))
room.on('error', (err) => console.error(err))Using React
@synento/react wraps the same client. The provider creates the room and
connects on mount; usePublishCamera publishes your camera and microphone, and
each VideoTile renders one remote participant:
import { useEffect, useState } from 'react'
import {
SynentoProvider,
VideoTile,
useParticipants,
usePublishCamera,
} from '@synento/react'
async function getToken() {
const res = await fetch('/api/connection', {
body: JSON.stringify({ sessionId: 'YOUR_SESSION_ID', userId: 'alice' }),
headers: { 'Content-Type': 'application/json' },
method: 'POST',
})
if (!res.ok) throw new Error('could not mint a connection token')
return res.json() // { wsUrl, token }
}
function Call() {
const [stream, setStream] = useState<MediaStream | null>(null)
useEffect(() => {
navigator.mediaDevices.getUserMedia({ audio: true, video: true }).then(setStream)
}, [])
usePublishCamera(stream) // publishes once the stream is ready
const participants = useParticipants()
return participants.map((id) => <VideoTile key={id} participantId={id} />)
}
export default function App() {
return (
<SynentoProvider getToken={getToken} userId="alice">
<Call />
</SynentoProvider>
)
}Browser support
Synento encodes with WebCodecs, so it needs a browser that has it: Chrome/Edge
94+ (tested on every CI run), or Safari 16.4+ and Firefox 133+ (they have the
required APIs, but a call has not yet been verified in them). See
Browser support for exactly what has been tested.
SynentoRoom.checkSupport() tells you before you try, so you can show a clear
message rather than failing at connect time.
When the session ends
Nothing else to do. The session's durable streams are the recording. It is immediately replayable and exportable to MP4, with no encoding step. See Recordings & Replay.