Quickstart: Call
Build an end-to-end encrypted video call in a web page: a project, a session, a token backend, a key endpoint and the browser SDK.
This guide builds a video call that several people join from a web page. The
call is end-to-end encrypted: Beam's Workers forward the frames without being
able to read them. You need an organization API key from the
Console, Node.js 20 or later, and two URLs of your
Beam environment, both from its configuration: the BeamCore API
(BEAM_CORE_URL) and the media directory (BEAM_MEDIA_DIRECTORY_URL). Beam
gives you both with access to an environment (the lab included); the SDKs have
no default directory.
1. Create a project, a key and a session
With the Beam CLI and your API key in BEAM_API_KEY
(the CLI reads the BeamCore API from BEAM_CORE_URL):
beam media project create my-app # prints mprj_...
beam media key generate --out media-key.json
beam media key add mprj_... --key-file media-key.json
beam media session create --project mprj_... --profile interactive --name "Daily" # prints msn_...media-key.json now holds the private signing key, its kid and the project
id. Keep it with your backend, out of source control.
The same with the API:
curl -X POST "$BEAM_CORE_URL/v1/media/sessions" \
-H "Authorization: Bearer $BEAM_API_KEY" -H "Content-Type: application/json" \
-d '{"project_id": "mprj_...", "delivery_profile": "interactive", "name": "Daily"}'An interactive session defaults to protection: {"mode": "e2ee", "key_provider": "customer"}:
your backend hands out the encryption keys. Create it with
--protection public (API: "protection": {"mode": "public"}) to skip step 3
for a first test; a public call needs no key endpoint.
2. The token backend
Your backend decides who may join and signs a token for them with the Node
server SDK (npm install express @beam-network/web-sdk-server). Save as
server.mjs next to media-key.json:
import express from "express";
import { randomBytes } from "node:crypto";
import { readFileSync } from "node:fs";
import {
MediaKeyIssuer,
MediaTokenSigner,
createMediaKeyEndpoint,
createMediaWebhookHandler,
} from "@beam-network/web-sdk-server/media";
const file = JSON.parse(readFileSync("media-key.json", "utf8"));
const SESSION = process.env.BEAM_MEDIA_SESSION; // msn_... from step 1
const signer = await MediaTokenSigner.create({
projectId: file.project_id,
keyId: file.kid,
privateKey: file.private_key, // the Ed25519 seed, base64url
});
const app = express();
app.use(express.static("public"));
app.post("/api/call/token", express.json(), async (req, res) => {
// Authenticate your own user here; this sample trusts the name it is sent.
const name = String(req.body.name ?? "guest").slice(0, 64);
const identity = `user-${randomBytes(6).toString("hex")}`;
const { token } = await signer.mint({ session: SESSION, role: "publish", identity, name, ttlSeconds: 3600 });
res.json({ token, directoryUrl: process.env.BEAM_MEDIA_DIRECTORY_URL });
});
app.listen(3000, () => console.log("http://localhost:3000"));
export { app, signer, SESSION };The identity is your user's id: the same identity joining twice replaces its first connection, so give every person their own.
3. The key endpoint (end-to-end encryption)
For an e2ee session with key_provider: "customer", the SDK asks your backend
for the session's frame keys before it publishes or decrypts anything. The key
endpoint must also refuse anyone you removed: a removed user's token can
still be valid for minutes, and if the endpoint answered it, the user would get
the new epoch's key too. Add to server.mjs:
// Epochs and sender counters MUST be persisted (your database): a restarted
// backend that reused a sender pair under the same key would break the
// encryption (one (key id, counter) per key). Both stores are two methods.
const epochs = {
current: (session) => db.currentEpoch(session), // starts at 1
bump: (session) => db.incrementEpoch(session),
};
const counters = { next: (session) => db.nextSenderCounter(session) }; // atomic, from 0
const issuer = new MediaKeyIssuer({
masterSecret: process.env.BEAM_MEDIA_MASTER_SECRET, // 32 random bytes, hex
epochs,
counters,
});
// Identities removed from the call, until their last token has expired. This
// deny list MUST be persisted too (your database, next to the epochs): a
// restarted backend that forgot it would hand a removed user the next epoch's
// key while their token is still valid.
const removed = {
add: (identity, until) => db.denyIdentity(SESSION, identity, until), // keeps the later `until`
list: () => db.deniedIdentities(SESSION, Math.floor(Date.now() / 1000)), // [{identity, until}] not expired
};
const TOKEN_TTL = 3600;
const keyEndpoint = createMediaKeyEndpoint({
issuer,
projectId: file.project_id,
keys: [{ kid: file.kid, public_key: file.public_key }],
deny: async () => ({ nonces: [], identities: await removed.list() }),
});
// Media webhooks: a participant left. Rotate the key; remember kicked identities.
const webhooks = createMediaWebhookHandler({
secret: process.env.BEAM_MEDIA_WEBHOOK_SECRET,
onEvent: async (event) => {
if (event.type !== "participant.left" || event.data.session_id !== SESSION) return;
if (["kicked", "token_revoked"].includes(event.data.reason))
await removed.add(event.data.identity, Math.floor(Date.now() / 1000) + TOKEN_TTL);
await epochs.bump(SESSION);
},
});
// Your own "remove" button: deny at once here, then kick through the Media API.
app.post("/api/call/kick", express.json(), async (req, res) => {
await removed.add(req.body.identity, Math.floor(Date.now() / 1000) + TOKEN_TTL);
const response = await fetch(`${process.env.BEAM_CORE_URL}/v1/media/sessions/${SESSION}/kick`, {
method: "POST",
headers: { Authorization: `Bearer ${process.env.BEAM_API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ identity: req.body.identity }),
});
if (!response.ok) {
// The kick did not happen: say so (the identity stays denied keys; retry the kick).
const error = await response.json().catch(() => null);
return res.status(502).json({ error: "kick_failed", code: error?.error ?? `http_${response.status}` });
}
await epochs.bump(SESSION);
res.status(204).end();
});
// The SDK handlers take a web Request and return a Response.
const toFetch = (handler) => async (req, res) => {
const request = new Request(`http://localhost${req.originalUrl}`, {
method: req.method,
headers: req.headers,
body: req.body,
});
const response = await handler(request);
res.status(response.status).set(Object.fromEntries(response.headers)).send(Buffer.from(await response.arrayBuffer()));
};
app.post("/api/media/keys", express.raw({ type: "*/*" }), toFetch(keyEndpoint));
app.post("/beam/webhooks", express.raw({ type: "*/*" }), toFetch(webhooks));- Each key document gives the caller a sender pair (
sender_index,sender_slot) from the per-session counter. Two senders must never share one, which is why the counter (and the epoch) live in your database, not in memory. The deny list of removed identities is persisted for the same reason: a backend that forgot it after a restart would serve a removed user's still valid token the next epoch's key.memorySenderCounterStore()andmemoryEpochStore()exist for a single process that never restarts, such as a test. - When someone leaves or is removed, the epoch moves on: the SDK re-fetches keys
after every
participant.leftevent and everyrefresh_after_ms. A removed identity no longer gets a document, so it cannot decrypt what follows. - Register the webhook with
beam media webhook create mprj_... --url https://your-backend/beam/webhooksand keep the printedwhsec_…secret inBEAM_MEDIA_WEBHOOK_SECRET. - Never send the master secret anywhere. Media Encryption explains the model.
Start the backend:
BEAM_CORE_URL=... BEAM_MEDIA_DIRECTORY_URL=... BEAM_API_KEY=... BEAM_MEDIA_SESSION=msn_... \
BEAM_MEDIA_MASTER_SECRET=$(openssl rand -hex 32) BEAM_MEDIA_WEBHOOK_SECRET=whsec_... node server.mjs4. The page
Install the browser SDK (npm install @beam-network/web-sdk) and bundle this
page with your usual tool, as public/index.html plus its script:
<input id="name" placeholder="Your name" />
<button id="join">Join</button>
<button id="leave" disabled>Leave</button>
<div id="tiles"></div>import { Call, customerKeyProvider } from "@beam-network/web-sdk/media";
const tiles = document.querySelector("#tiles")!;
let call: Call | null = null;
document.querySelector("#join")!.addEventListener("click", async () => {
const name = (document.querySelector("#name") as HTMLInputElement).value;
const { token, directoryUrl } = await fetch("/api/call/token", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
}).then((response) => response.json());
call = await Call.join(token, {
directoryUrl,
e2ee: { keyProvider: customerKeyProvider({ url: "/api/media/keys" }) },
});
// Every remote track is subscribed by default; attach it when it plays.
call.on("track.subscribed", (track) => {
const element = track.attach(); // a <video> or <audio>, sized to its tile
element.id = track.id;
tiles.append(element);
});
call.on("track.unsubscribed", (track) => document.getElementById(track.id)?.remove());
call.on("speakers.changed", ({ dominantId }) => console.log("speaking:", dominantId));
call.on("closed", ({ reason }) => console.log("call closed:", reason));
await call.publishCamera();
await call.publishMicrophone();
(document.querySelector("#leave") as HTMLButtonElement).disabled = false;
});
document.querySelector("#leave")!.addEventListener("click", () => call?.leave());connect(token, options) does the same and returns a Call, Stage or
Player from the session's profile, when one page serves several kinds of
session. With a strict Content Security Policy, serve the SDK's
sframe-worker.js and pass e2ee: { keyProvider, workerUrl }.
Open http://localhost:3000 in two browsers, join from both, and each sees the
other.
What happens
Call.joinjoins the media directory with the token and receives the SFU's WHIP and WHEP endpoints, ranked for the user.- It fetches the key document, then publishes camera and microphone over WHIP
(VP8 simulcast and Opus, each frame encrypted with SFrame) and opens one WHEP
connection carrying the event channel (
participant.joined,track.published,speakers.changed, …). RemoteTrack.attachfollows the tile's size, and the SFU forwards the simulcast layer that fits it.- On network changes it restarts ICE; when a Worker is drained or fails it re-joins the directory and reconnects on its own.
Next
- Mute and screen share:
call.mute("microphone", true),call.publishScreen(). - Remove someone: the
/api/call/kickroute above (Media API kick, the identity denied by the key endpoint, a new epoch). - Know who joined and left on your backend with webhooks.
- Add a bot or an AI voice agent: Server-side Participants.