API
What you can call today
Quickstart
The quickstart and the downloadable example go from an account to a phone camera.
npm package
@peerkit-dev/sdk version 0.1.6 is on the npm registry. The example pins that version in package-lock.json.
Prerequisites
Node.js 22 or newer, a phone with a camera, and a browser on this computer. No Docker, database, or media server is required.
Account and organization
- Create an account at peerkit.dev/sign-up.
- Open the dashboard and create or select an organization. PeerKit rejects a signed-in user who has none.
- Opening the dashboard creates that organization's project.
New organizations start on Free: 60 streaming minutes each UTC month, one open session, and at most 15 minutes per session. See pricing for Starter and Pro.
API key
- Open API keys.
- Name the key and create it. Copy the secret when it appears. PeerKit stores only a hash, so it cannot be shown again.
- Put that secret in the example
.envasPEERKIT_API_KEY. Send it only from your server, asAuthorization: Bearer pk_live_….
API keys and participant tokens
A server API key authorizes the Node process. It starts with pk_live_. It never belongs in a browser, a phone page, or a client bundle.
A participant token is short-lived. The phone and the hosted viewer receive it by opening https://peerkit.dev/s with the invitation secret in the URL fragment. That token is not an API key. The example page does not join the session.
Download and configure
- Unzip it into an empty folder.
- Copy
.env.exampleto.env. - Set
PEERKIT_API_KEY. LeavePEERKIT_API_URL=https://api.peerkit.dev. Invitation pages are hosted athttps://peerkit.dev/s.
Start
From the example folder:
npm ci npm start
Open http://127.0.0.1:4010 on this computer. The phone opens the hosted invitation from the QR code.
Phone
- Enter an optional session name, up to 100 characters. It is a label, not part of the invitation.
- Leave one-way microphone audio unchecked for video only. Check it to allow the phone to publish its microphone. The phone asks for permission only after Enable microphone. The viewer does not send audio back.
- Click Create session.
- Scan the QR code, allow the camera, and tap Start. If the session includes audio, tap Enable microphone and allow it.
- Click Open viewer on this computer.
- Click End session when you are done so the open-session slot is free.
Restarting the example reuses an open session. After End session, or after the session expires, Create session replaces the QR code and the viewer link. A missing API key stops the process before it listens.
Server code
This is the whole server call. Omit name to leave the session unnamed. Omit audio for video only. The example lets PeerKit choose the duration, so a Free session stays within 15 minutes.
import { PeerKit } from "@peerkit-dev/sdk/server";
const apiKey = process.env.PEERKIT_API_KEY;
if (!apiKey) throw new Error("Missing PEERKIT_API_KEY");
const peerkit = new PeerKit({
apiKey,
apiUrl: "https://api.peerkit.dev",
});
const session = await peerkit.createSession({
name: "Loading dock",
audio: true,
});
const camera = await peerkit.createInvitation(session.id, "publisher");
const viewer = await peerkit.createInvitation(session.id, "viewer");Data — Messaging & File Transfer
The downloaded example stays on the camera path. A data session uses the same server client with media: "data". It does not request a camera or microphone. Both people can send text messages, binary data, and files. Call acceptFile only after the person chooses to receive the file.
import { PeerKitSession } from "@peerkit-dev/sdk";
const session = await peerkit.createSession({ media: "data", name: "File Transfer" });
const first = await peerkit.createInvitation(session.id, "publisher");
const second = await peerkit.createInvitation(session.id, "viewer");
const data = new PeerKitSession({
signalingUrl: access.signalingUrl,
token: access.participantToken,
media: "data",
});
data.on((event) => {
if (event.type === "dataMessage" && typeof event.data === "string") console.log(event.data);
if (event.type === "fileTransfer" && event.transfer.status === "incoming") showIncoming(event.transfer);
if (event.type === "fileTransfer" && event.transfer.status === "complete" && event.transfer.direction === "receive") {
const blob = data.receivedFile(event.transfer.id);
console.log(blob?.size, event.transfer.name);
}
});
await data.connect();
data.sendText("ready");
data.sendFile(file);
data.acceptFile(incomingId);Voice Core
@peerkit-dev/voice-core is Voice Core: VoiceController for vanilla JavaScript and the <peerkit-voice> element. @peerkit-dev/voice is the React component and depends on that core. Create the session with media: "audio". Call start() from a click so the browser can request the microphone and play remote audio. A session you pass in stays connected on end unless you set disconnectOnEnd. Full examples are on the Voice component page.
import { VoiceController } from "@peerkit-dev/voice-core";
const call = new VoiceController(() => ({
invitationUrl: "https://peerkit.dev/s#inv_…",
}));
call.attachAudio(document.querySelector("audio"));
call.sync();
document.querySelector("#start")?.addEventListener("click", () => {
void call.start();
});Call Core
@peerkit-dev/call-core is Call Core: CallController for vanilla JavaScript and the <peerkit-call> element. @peerkit-dev/call is the React component and depends on that core. Create the session with media: "call". Call start() from a click so the browser can request the camera and microphone. A session you pass in stays connected on end unless you set disconnectOnEnd. Screen sharing does not send system audio. Full examples are on the Call component page.
import { CallController } from "@peerkit-dev/call-core";
const call = new CallController(() => ({
invitationUrl: "https://peerkit.dev/s#inv_…",
}));
call.attachPreview(document.querySelector("#preview"));
call.attachRemoteVideo(document.querySelector("#remote"));
call.attachAudio(document.querySelector("audio"));
call.sync();
document.querySelector("#start")?.addEventListener("click", () => {
void call.start();
});Components
PeerKit components cover messaging, file sharing, recording, voice, and video. The JavaScript SDK does not depend on React. Record, Chat, Share, Voice, and Call each ship as a headless controller, a custom element, and a React component.
- Record —
@peerkit-dev/record-coreand@peerkit-dev/record.<peerkit-record>needs no session. - Chat —
@peerkit-dev/chat-coreand@peerkit-dev/chat. Element:<peerkit-chat>. - Share —
@peerkit-dev/share-coreand@peerkit-dev/share. Element:<peerkit-share>. - Voice —
@peerkit-dev/voice-coreand@peerkit-dev/voice. Controller:VoiceController. Element:<peerkit-voice>. - Call —
@peerkit-dev/call-coreand@peerkit-dev/call. Controller:CallController. Element:<peerkit-call>.
The component catalog has live demos. Install commands and short examples are on each component page. For WordPress sites, see PeerKit for WordPress — PeerKit Chat is the first plugin; other components stay on the developer packages today.
Five-minute challenge
The five-minute challenge is a Vite + TypeScript demo that joins with the browser SDK while the phone uses the hosted invitation page.
Goal
From a fresh project, install @peerkit-dev/sdk@0.1.6, paste a small example, open a browser, scan a QR code with a phone, and establish a real PeerKit connection in about five minutes.
Exact commands
From a blank Vite app:
npm create vite@latest peerkit-challenge -- --template vanilla-ts cd peerkit-challenge npm install npm install @peerkit-dev/sdk@0.1.6 npm run dev
Or download the complete working example (server, UI, QR, timer, Camera / Audio / Data):
Download the five-minute challenge
unzip peerkit-five-minute-challenge.zip cd peerkit-five-minute-challenge cp .env.example .env # Paste PEERKIT_API_KEY from https://peerkit.dev/dashboard/keys npm install npm run dev
Open http://127.0.0.1:5173. Leave PEERKIT_API_URL=https://api.peerkit.dev.
Authentication
Create a server API key at API keys. Put it in .env as PEERKIT_API_KEY. The key starts with pk_live_ and must never appear in browser code, client bundles, or invitation URLs.
Participant tokens
The browser redeems an invitation secret for a short-lived participant token, then refreshes that token while the session is open. Neither step uses the API key.
Working example
Server session creation:
import { PeerKit } from "@peerkit-dev/sdk/server";
const peerkit = new PeerKit({
apiKey: process.env.PEERKIT_API_KEY!,
apiUrl: "https://api.peerkit.dev",
});
const session = await peerkit.createSession({ name: "Challenge" });
const phone = await peerkit.createInvitation(session.id, "publisher");
const browser = await peerkit.createInvitation(session.id, "viewer");Browser join with the SDK:
import { PeerKitSession } from "@peerkit-dev/sdk";
const redeemed = await fetch("/api/redeem", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ token: invitationToken }),
});
const access = await redeemed.json();
const session = new PeerKitSession({
signalingUrl: access.signalingUrl,
token: access.participantToken,
tokenExpiresAt: access.tokenExpiresAt,
});
session.attachVideo(videoElement);
await session.connect();Phone connection
- Click Start on the elapsed timer, choose Camera, Audio, or Data, then Create session.
- Scan the large QR code. The phone opens
https://peerkit.dev/swith the invitation in the fragment. - Allow camera or microphone permissions on the phone and join.
- Watch the desktop page connect with
PeerKitSession. The timer records the real time to first connection.
What each mode shows
- Camera — phone publishes; desktop watches remote video. Optional one-way phone microphone audio is not two-way talkback.
- Audio —
media: "audio"microphone-only call with mute and activity indication. - Data — text messages, file transfer with progress, accept, and download.
Troubleshooting
Missing PEERKIT_API_KEY— copy.env.exampleto.envand paste a key from the dashboard.concurrency_limited— Free plans allow one open session. End the previous session first.- QR will not scan — keep the invitation in the QR only. Do not log invitation URLs; the fragment is the secret.
- Browser connects but no video — on the phone, allow the camera and tap Start on the hosted join page.
- Audio silent — tap Hear the call and Turn on microphone after a user gesture on both sides.
Measured completion time
Validated on 15 October 2026 from a clean directory against production api.peerkit.dev with @peerkit-dev/sdk@0.1.6:
npm install→ listening app → Create session with QR and redeemable participant token: 4.5 seconds machine time (install 1.5s, server ready 3.2s).- Playwright walkthrough (camera, audio, data session creation, QR, local SDK join, cleanup): 4 passed in 12.4s.
Those numbers exclude account creation, API key pasting, and a physical phone scan. Use the on-page timer to record your own time to first real connection.
Automated walkthrough
Playwright creates real production sessions, asserts the QR, joins from Chromium with the SDK, writes screenshots and video under test-results/, and ends each session. It does not fake a WebRTC connection. It also cannot operate a physical phone camera.
npx playwright install chromium npm run test:e2e
Authenticate with a Clerk session from the dashboard or with Authorization: Bearer pk_live_… from your server. Browsers receive short-lived participant tokens, not API keys. API keys follow the same organization minute, duration, and concurrency limits as the dashboard.
Billing
Minutes and concurrent sessions are shared by every project in the organization. Time counts while a camera video producer is forwarded to a connected viewer. Free resets at 00:00 UTC on the first of the month. Starter and Pro follow the Stripe billing period once checkout is configured. Until then, paid subscriptions are not available and pricing offers an availability signup for those plans. Enterprise uses contact. The free plan and the quickstart stay available.
Endpoints
| Method | Path | Purpose |
|---|---|---|
| POST | /v1/sessions | Create a session. Optional name, up to 100 characters. Omit media for a camera. media audio creates an audio call. media data sends text, binary data, and files with no camera or microphone. Optional voice applies only to a camera. |
| GET | /v1/sessions | List sessions for the current project, 20 per page, newest first. Use page. |
| GET | /v1/sessions/:id | Read a session in your organization. |
| PATCH | /v1/sessions/:id | Set or clear the session name. Same organization and project rules as reading it. |
| POST | /v1/sessions/:id/end | End it and disconnect participants. |
| POST | /v1/sessions/:id/invitations | Create or reuse the publisher or viewer invitation. Pass additional true for another viewer on a camera session. |
| POST | /v1/invitations/redeem | Exchange an invitation for a participant token. |
| POST | /v1/participants/refresh | Refresh a participant token while the session is active. |
| POST | /v1/projects/:id/channels | Create a named channel in that project. |
| GET | /v1/projects/:id/channels | List channels that are not archived. |
| GET | /v1/channels/:id | Read a channel and its open session, if one exists. No invitation secret. |
| GET | /v1/channels/:id/public | The channel name only. No authentication, session, or invitation. |
| PATCH | /v1/channels/:id | Rename a channel. The address stays the same. |
| POST | /v1/channels/:id/archive | Archive a channel. It cannot start another session. |
| POST | /v1/channels/:id/sessions | Start the next session, or return the open one with its original media. The body matches POST /v1/sessions, including media video, audio, data, or call. Voice applies only to a camera. |
| POST | /v1/projects/:id/api-keys | Create an API key. The secret is returned once. |
| POST | /v1/api-keys/:id/revoke | Revoke a key. |
| POST | /v1/projects/:id/webhooks | Register an HTTPS endpoint. Deliveries are signed and retried. |
Viewer SDK
import { PeerKitSession } from "@peerkit-dev/sdk";
async function joinViewer(invitationUrl: string, video: HTMLVideoElement) {
const invitationToken = decodeURIComponent(new URL(invitationUrl).hash.replace(/^#/, ""));
const redeemed = await fetch("https://api.peerkit.dev/v1/invitations/redeem", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ token: invitationToken }),
});
if (!redeemed.ok) throw new Error("Invitation could not be opened");
const access = await redeemed.json();
let participantToken = access.participantToken;
const session = new PeerKitSession({
signalingUrl: access.signalingUrl,
token: participantToken,
tokenExpiresAt: access.tokenExpiresAt,
slots: true,
refreshToken: async () => {
const refreshed = await fetch("https://api.peerkit.dev/v1/participants/refresh", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ token: participantToken }),
});
if (!refreshed.ok) throw new Error("Session access could not be refreshed");
const next = await refreshed.json();
participantToken = next.participantToken;
return { token: next.participantToken, expiresAt: next.tokenExpiresAt };
},
});
session.attachVideo(video);
session.setDisplayedSlots(["camera:1"]);
await session.connect();
return session;
}The hosted camera page is for the phone. Customer applications embed the viewer and keep their API key on a server. Install @peerkit-dev/sdk from npm. Pass slots: true and call setDisplayedSlots when the page shows a subset of cameras. Role-only createInvitation(id, "viewer") reuses the original viewer; { role: "viewer", additional: true } creates another. The quickstart example is the supported way to try the server entry.
Screen sharing
On a camera session, the camera invitation can share a screen, window, or browser tab with publishScreen. The browser shows its own picker after an explicit click. Screen sharing needs HTTPS or localhost and a browser that provides getDisplayMedia (desktop Chrome and Safari do; many phone browsers do not). A missing API, a denied permission, and a cancelled picker are separate outcomes. It does not consume an extra camera entitlement. The same camera invitation can publish camera and screen together, or screen alone. A camera-session viewer token also includes publish:screen, so that viewer can share a desktop without gaining publish:video or another camera slot. The camera page and other viewers receive that screen. Viewers bind a remote screen with attachScreen. Track events and producerClosed include source: "screen". Audio and data sessions do not include screen sharing. System audio from the display picker is not mixed into PeerKit’s microphone path; use enableMicrophone for mic audio. Call Core uses this screen path on a media: "call" session. Stopping the share restores the camera when it was on before the share.
import { PeerKitSession, screenCaptureSupported } from "@peerkit-dev/sdk";
if (!screenCaptureSupported()) throw new Error("Screen sharing is not supported");
session.attachScreen(screenVideo);
session.on((event) => {
if (event.type === "screen") console.log(event.state, event.message);
if (event.type === "track" && event.source === "screen") { /* remote screen */ }
});
await session.publishScreen();
// await session.stopPublishingScreen();Session names
name is optional on create and on PATCH /v1/sessions/:id. PeerKit trims it and keeps at most 100 characters. An empty name is stored as unnamed. The dashboard then shows Session, with the short id beside it. A name is a label for people using the dashboard. It is not part of the invitation.
Audio calls
media: "audio" creates a call for two people. Neither token includes a camera capability. Both can publish a microphone and both can subscribe to the other microphone. This is not voice: "two-way". Two-way voice is talkback during a camera session, and the server still refuses it unless the organization is allowlisted.
import { PeerKit } from "@peerkit-dev/sdk/server";
import { PeerKitSession } from "@peerkit-dev/sdk";
const peerkit = new PeerKit({ apiKey, apiUrl: "https://api.peerkit.dev" });
const session = await peerkit.createSession({ media: "audio", name: "Support" });
const first = await peerkit.createInvitation(session.id, "publisher");
const second = await peerkit.createInvitation(session.id, "viewer");
const call = new PeerKitSession({
signalingUrl: access.signalingUrl,
token: access.participantToken,
media: "audio",
});
call.attachAudio(audioElement);
await call.connect();
await call.enableMicrophone();
await call.setMicrophoneMuted(false);
call.disconnect();Redeem each invitation the same way as a viewer token, then construct PeerKitSession with that participant token. enableMicrophone is the user gesture that asks for permission, and it requests audio only. setMicrophoneMuted silences the outgoing microphone. attachAudio and enableSound play the other person. disconnect leaves the call and releases the microphone. endSession closes it for both people. A denied microphone stays off until the person tries again. A dropped connection reconnects with the same participant. The hosted join page does this for both links. Voice Core wraps this session in VoiceController and <peerkit-voice>. The Voice component page has the JavaScript, HTML, and React examples.
Data — Messaging & File Transfer
media: "data" creates a session for two people to send text messages, binary data, and files. Both tokens carry data:send and data:receive only. The page does not ask for a camera or microphone. Camera sessions and audio calls can also carry text and files between the people already in the session. Tokens from @peerkit-dev/sdk@0.1.3 still join. They do not open a data channel. Text and files inside a camera or audio session shipped in @peerkit-dev/sdk@0.1.4. media: "data" is in @peerkit-dev/sdk@0.1.5. Additional viewers and camera subscription filtering are in @peerkit-dev/sdk@0.1.6. The hosted camera, viewer, audio, and data pages send and receive files on this same session.
sendText uses one reliable, ordered data channel per participant. A file is chunked, paced with bufferedAmount, and checked with SHA-256 after the receiver accepts it. The receiver must call acceptFile or rejectFile. Nothing is opened or executed. receivedFile returns a Blob the page can download. File bytes are not sent through PeerKit signaling and are not stored on PeerKit servers. The data channel is encrypted in transit. TURN may relay it when a direct path is unavailable. The default limit is 100 MB, and a page can set maxFileBytes up to 512 MB.
import { PeerKit } from "@peerkit-dev/sdk/server";
import { PeerKitSession } from "@peerkit-dev/sdk";
const peerkit = new PeerKit({ apiKey, apiUrl: "https://api.peerkit.dev" });
const session = await peerkit.createSession({ media: "data", name: "File Transfer" });
const first = await peerkit.createInvitation(session.id, "publisher");
const second = await peerkit.createInvitation(session.id, "viewer");
const data = new PeerKitSession({
signalingUrl: access.signalingUrl,
token: access.participantToken,
media: "data",
});
data.on((event) => {
if (event.type === "dataMessage" && typeof event.data === "string") console.log(event.data);
if (event.type === "fileTransfer" && event.transfer.status === "incoming") showIncoming(event.transfer);
if (event.type === "fileTransfer" && event.transfer.status === "complete" && event.transfer.direction === "receive") {
const blob = data.receivedFile(event.transfer.id);
console.log(blob?.size, event.transfer.name);
}
});
await data.connect();
data.sendText("ready");
data.sendFile(file);
data.acceptFile(incomingId);Accepting a file in this example is explicit in your code. The hosted pages ask the person first. Do not accept files automatically in a product UI. Treat the file name and media type as untrusted text.
Camera audio
Omit audio and voice, or send audio: false or voice: "off", for video only. audio: true and voice: "one-way" are the same mode: the phone may publish a microphone and the viewer may subscribe. Existing one-way tokens keep that behavior. voice: "two-way" also lets the viewer publish a microphone and the phone subscribe to it. The server refuses two-way unless the organization is on the two-way allowlist. One pilot organization is listed. Two-way is not generally available, and it is not part of the plan prices.
Each side shows Enable microphone only when its token includes publish:audio. That tap is what asks for microphone permission. A video-only session never does. Mute microphone stops the audio that side is sending. Mute sound and the volume slider change playback on that page only. Enable sound satisfies the browser autoplay rule. The viewer chooses Selected camera or All cameras. Changing the video selection does not change who hears them. The media server sends the viewer microphone only to the cameras in that choice. Cameras do not hear each other. Stop camera releases that phone’s video, microphone, and the viewer’s voice on that phone. Start does not turn the microphone back on. Leave, ending the session, expiry, and another phone taking over release the capture and playback for that participant.
The browser is asked to cancel echo and reduce noise. That does not guarantee either side will avoid hearing its own speaker. Camera count follows the organization plan: Free 1, Starter 2, Pro 4. Each camera joins on its own invitation. New camera sessions allow up to four viewers, who can select and switch among connected cameras. Recording the grid, or a separate file per camera, is planned and is not available. Those files would stay in this browser. Server recording and storage is a different, later feature. A channel is available now: it is a named destination, and each broadcast is still one session with its own invitations. The address/c/<channelId> does not open the camera or reveal an invitation. A channel is a destination, not the WebRTC data channel used for files.
Local recording
The hosted viewer records the selected camera. The recording panel says which audio will be included before recording starts. A video-only file does not include a microphone. A one-way file includes that camera’s microphone. A two-way file also includes the viewer’s voice while that voice is addressed to the camera being recorded. Other cameras are not included, and the file does not record the page’s playback mix. Mute and volume on the viewer do not change the recorded audio. Muting a microphone does. Mirror view changes this display only. The recording keeps the image as received. Switching the phone between front and rear cameras continues this recording. The last frame stays up until the new camera appears. It stays in this browser until you download or discard it, for up to 10 minutes or 100 MB. Nothing is uploaded. The download is WebM or MP4, matching the format the browser recorded. Record is available only while the camera picture is coming through. Stop recording saves the file and leaves the live camera running. Download or discard that file before starting another. A front or rear camera switch keeps the same recording, the same timer, and the same file. During the switch the recording holds the last frame, then fits the new picture inside that frame without stretching it. The recording stops if the camera is stopped, another publisher takes over, the viewer disconnects, the session ends or expires, or a switch does not recover within 8 seconds. It does not continue on a stream that was not part of that switch. The page warns before a reload or navigation while a recording is in progress or not yet downloaded. While that recording is running, the phone shows “Viewer is recording”. The indicator follows PeerKit’s recording control. It cannot detect screen recording outside PeerKit.