# Metered — Complete API & SDK Reference
(last updated: 2026-05-12)
> Metered provides real-time communication infrastructure: a Video/Voice SDK, TURN Server Service, Global Cloud SFU, and Realtime Messaging. This file combines product references — for Realtime Messaging see the dedicated file below.
For individual product files, see: https://www.metered.ca/docs/llms.txt
**Realtime Messaging** has its own dedicated reference (large surface, distinct protocol):
- https://www.metered.ca/docs/llms-realtime-messaging.txt — WebSocket pub/sub + direct messaging covering WebRTC signalling, AI agent communication, IoT telemetry, presence/chat, and collaborative apps. Built-in TURN integration via `metadata.iceServers` in the JWT.
---
## Part 1: Video SDK
# Metered Video SDK — llms.txt reference
Metered Video is a real-time video and audio calling SDK. It lets you build group video/audio
calling apps, live streaming, recording, composition, and RTMP-out to third-party services.
## Getting Started
1. **Sign up** at https://dashboard.metered.ca/signup to create a free Metered account.
2. After signup your app is created automatically. Your **app name** (e.g. `yourappname`) forms your domain: `yourappname.metered.live`. Find it on the Dashboard home page.
3. Go to **Dashboard → Developers** to find your **Secret Key**. This is used for all server-side REST API calls. Never expose it in front-end code.
4. Rooms are created via the Dashboard or the REST API. Each room has a URL: `yourappname.metered.live/roomName`.
**Two dashboards.** Metered has a redesigned dashboard (https://dashboard.metered.ca/v2) and the classic dashboard; both manage the same account, and the API is identical. Users switch with the **Old dashboard** button (new → classic) or by opening /v2 (classic → new). Navigation map (new → classic):
- Video API & SDK → **Rooms** → *Create room* ↔ Dashboard → *Create Room*
- Rooms list → the room's **⋮** menu → *Edit* (the same form as Create room; *Update room* saves) ↔ Rooms → edit button / Room Summary → *Edit Room*
- Room form sections: Identity · iFrame options · Recording & composition (*Record individual streams* ↔ *Record Room*; *Record composition*; *Enable composition*; *Composition layout*) · Streaming output (*HLS / DASH live streaming*; *Push to external RTMP destination* + *RTMP OUT URL* ↔ *Enable RTMP OUT*) · Watermark (*Enable watermark overlay*) · Timing & limits · Webhooks
- Room page (**⋮** → *View*): *Live streaming (HLS/Dash)* row with the .m3u8 URL, *Stream ID* row, *Embed snippet* ↔ Room Summary → HLS Live Stream URL, Embed Info
- Video API & SDK → **Cloud Recordings** → *Preview* (side panel: preview player, *Download*, *Delete*) ↔ Cloud Recording → *View* → recording page
- **Developers** → secret key hidden until *Reveal* ↔ Developers → secret key shown
- The *Broadcaster* composition layout is not in the new dashboard's layout menu yet; set it on the classic dashboard.
CDN import (JavaScript):
```
```
REST API base URL:
```
https://.metered.live/api/v1
```
Authentication: pass `secretKey` as a query parameter on every REST call (e.g. `?secretKey=YOUR_SECRET_KEY`).
Key concepts:
- Room: a meeting space with a unique URL (`.metered.live/`).
- Session (meetingSession): one call that happened inside a room.
- Participant Session: one user's participation in a session.
---
## Setup
```javascript
// 1. Include SDK
//
// 2. Create meeting object
const meeting = new Metered.Meeting();
// 3. Join a room
const meetingInfo = await meeting.join({
roomURL: "yourapp.metered.live/your-room-name",
name: "John Doe"
});
// 4. Share camera / mic
await meeting.startVideo();
await meeting.startAudio();
// 5. Handle remote streams
meeting.on("remoteTrackStarted", function(trackItem) {
var stream = new MediaStream([trackItem.track]);
var video = document.createElement("video");
video.id = trackItem.streamId;
video.autoplay = true;
video.srcObject = stream;
document.getElementById("container").append(video);
});
meeting.on("remoteTrackStopped", function(trackItem) {
document.getElementById(trackItem.streamId).remove();
});
// 6. Leave
await meeting.leaveMeeting();
```
---
## SDK Methods
All methods are called on the `meeting` object (`new Metered.Meeting()`).
### join(options)
Join a meeting room. Must be called before any media methods.
```javascript
const meetingInfo = await meeting.join(options);
```
| Parameter | Type | Required | Description |
|---|---|---|---|
| roomURL | string | yes | `.metered.live/` |
| name | string | yes | Display name for the participant |
| accessToken | string | no | Token from `/api/v1/token`. Required for private rooms |
| receiveVideoStreamType | string | no | `only_individual` (default), `none`, `only_composed`, `all` |
| receiveAudioStreamType | string | no | `only_individual` (default), `none`, `only_composed`, `all` |
Returns `meetingInfo`:
```
{
roomId: string,
meetingSessionId: string,
participantSessionId: string,
onlineParticipants: [{ _id, name, isAdmin, meetingSessionId, roomId }]
}
```
### leaveMeeting()
Leave the meeting. Emits `stateChanged`, `meetingLeft` to self and `participantLeft` to others.
```javascript
await meeting.leaveMeeting();
```
Returns: void
### startVideo()
Share the participant's camera. Browser will prompt for camera permission. **Must call `join()` first.**
```javascript
await meeting.startVideo();
```
Returns: void. Emits `localTrackStarted` (type "video").
### stopVideo()
Stop sharing camera or screen. Emits `localTrackStopped` to self, `remoteTrackStopped` to others.
```javascript
await meeting.stopVideo();
```
Returns: void
### startAudio()
Share the participant's microphone. Browser will prompt for mic permission. **Must call `join()` first.**
```javascript
await meeting.startAudio();
```
Returns: void. Emits `localTrackStarted` (type "audio").
### stopAudio()
Stop sharing microphone. Emits `localTrackStopped` to self, `remoteTrackStopped` to others.
```javascript
await meeting.stopAudio();
```
Returns: void
### startScreenShare()
Share the participant's screen. Shows browser popup to select screen/window/tab. Replaces camera feed if one is active. **Must call `join()` first.**
```javascript
await meeting.startScreenShare();
```
Returns: void. Emits `localTrackStarted` (type "video") if no camera was active, or `localTrackUpdated` if replacing an existing camera feed.
### muteLocalAudio()
Mute microphone without stopping the audio stream. `remoteTrackStopped` is NOT emitted. Browser still shows mic as in use.
```javascript
await meeting.muteLocalAudio();
```
Returns: void
### unmuteLocalAudio()
Unmute previously muted microphone. `remoteTrackStarted` is NOT emitted.
```javascript
meeting.unmuteLocalAudio();
```
Returns: void
### pauseLocalVideo()
Mute video (black frame sent) without stopping the video stream. `remoteTrackStopped` is NOT emitted.
```javascript
await meeting.pauseLocalVideo();
```
Returns: void
### resumeLocalVideo()
Resume previously paused video. `remoteTrackStarted` is NOT emitted.
```javascript
await meeting.resumeLocalVideo();
```
Returns: void
### listVideoInputDevices()
List all cameras connected to the device. Browser will prompt for camera permission.
```javascript
const devices = await meeting.listVideoInputDevices();
// => [{ deviceId: string, groupId: string, label: string }]
```
Returns: Array of `{ deviceId, groupId, label }`
### listAudioInputDevices()
List all microphones connected to the device. Browser will prompt for mic permission.
```javascript
const devices = await meeting.listAudioInputDevices();
// => [{ deviceId: string, groupId: string, label: string }]
```
Returns: Array of `{ deviceId, groupId, label }`
### listAudioOutputDevices()
List all speakers/audio-output devices. Not supported in Firefox.
```javascript
const devices = await meeting.listAudioOutputDevices();
// => [{ deviceId: string, groupId: string, label: string }]
```
Returns: Array of `{ deviceId, groupId, label }`
### chooseVideoInputDevice(deviceId)
Select or switch camera. Can be called before or after join().
```javascript
await meeting.chooseVideoInputDevice(deviceId);
```
| Parameter | Type | Required | Description |
|---|---|---|---|
| deviceId | string | yes | From `listVideoInputDevices()` |
Returns: void
### chooseAudioInputDevice(deviceId)
Select or switch microphone. Can be called before or after join().
```javascript
await meeting.chooseAudioInputDevice(deviceId);
```
| Parameter | Type | Required | Description |
|---|---|---|---|
| deviceId | string | yes | From `listAudioInputDevices()` |
Returns: void
### chooseAudioOutputDevice(deviceId)
Select or switch speaker. Not supported in Firefox.
```javascript
await meeting.chooseAudioOutputDevice(deviceId);
```
| Parameter | Type | Required | Description |
|---|---|---|---|
| deviceId | string | yes | From `listAudioOutputDevices()` |
Returns: void
### getOnlineParticipants()
Return the list of participants currently in the meeting. Synchronous call.
```javascript
const participants = meeting.getOnlineParticipants();
```
Returns: Array of `{ _id, name, isAdmin: boolean, meetingSessionId, roomId }`
### getLocalVideoStream()
Get the MediaStream of the selected (or default) video input device.
```javascript
var stream = await meeting.getLocalVideoStream();
```
Returns: MediaStream. Throws if no video device available.
### shareCustomVideoTrack(videoTrack)
Share a custom video MediaStreamTrack (e.g., from a canvas or processed stream) instead of the camera. join() must be called first.
```javascript
await meeting.shareCustomVideoTrack(videoTrack);
```
| Parameter | Type | Required | Description |
|---|---|---|---|
| videoTrack | MediaStreamTrack | yes | Video track to share |
Returns: MediaStreamTrack. Emits `localTrackStarted` (first time) or `localTrackUpdated` (replacing existing).
### shareCustomAudio(audioStream)
Share a custom audio MediaStream (e.g., from Web Audio API) instead of the microphone. join() must be called first.
```javascript
await meeting.shareCustomAudio(audioStream);
```
| Parameter | Type | Required | Description |
|---|---|---|---|
| audioStream | MediaStream | yes | Stream containing an audio track |
Returns: void. Emits `localTrackStarted` when no prior audio producer exists. Unlike video, replacing an existing audio track does NOT emit `localTrackUpdated`.
---
### sendChatMessage(text)
Send a text chat message to everyone in the meeting. Requires `join()`. Rate limit 20 messages / 10s.
```javascript
meeting.sendChatMessage("hello");
```
Returns: void. Others receive `chatMessageReceived`.
### sendChatMessageTo(participantSessionId, text)
Send a text message to ONE participant only (private). `participantSessionId` is the `_id` from `participantJoined` / `join()`. Sender and recipient both receive `chatMessageReceived` with `recipientParticipantSessionId` set; no one else sees it (also hidden from others in history).
### sendChatFileMessage(fileS3Key, fileName, fileMimeType, fileSizeBytes)
Send a file message referencing a file previously uploaded via `POST /api/v1/chat/upload` (use `getChatAccessToken()` as the bearer). Recipients receive `chatMessageReceived` (type "file" or "image") carrying a `downloadToken`.
### sendChatFileMessageTo(participantSessionId, fileS3Key, fileName, fileMimeType, fileSizeBytes)
Directed (private) file message to one participant.
### getChatHistory(before, limit, beforeId)
Request chat history; results arrive on the `chatHistory` event (not a return value). `before` = ISO date of the oldest message you have; `limit` = page size (default 50, max 100); `beforeId` = its `_id` (stable cursor). When the room's chat history retention is Off, history is served from the SDK's in-session buffer. Rate limit 10 / 10s.
### sendTypingIndicator()
Broadcast that this participant is typing; others receive `chatTyping`. Throttled to one broadcast per 2s.
### getChatRoomId()
Returns the chat room id (string), or "" when the room has chat disabled.
### getChatAccessToken()
Returns the bearer token for the chat file REST endpoints (`POST /api/v1/chat/upload`, `GET /api/v1/chat/file/:messageId`). Send as `Authorization: Bearer `.
## SDK Events
All events are listened to via `meeting.on(eventName, callback)`.
### localTrackStarted
Fired when `startAudio()`, `startVideo()`, `startScreenShare()`, `shareCustomVideoTrack()`, or `shareCustomAudio()` is called.
```javascript
meeting.on("localTrackStarted", function(localTrackItem) { });
```
Callback data (`localTrackItem`):
| Field | Type | Description |
|---|---|---|
| type | string | `"audio"` or `"video"` |
| streamId | string | Unique stream identifier |
| track | MediaStreamTrack | The media track |
### localTrackStopped
Fired when `stopAudio()`, `stopVideo()` is called, or when custom tracks end.
```javascript
meeting.on("localTrackStopped", function(localTrackItem) { });
```
Callback data: same shape as `localTrackStarted`.
### localTrackUpdated
Fired when an existing local track is replaced (e.g., `shareCustomVideoTrack()` while already sharing, switching devices, switching between camera and screen share).
```javascript
meeting.on("localTrackUpdated", function(localTrackItem) { });
```
Callback data: same shape as `localTrackStarted`.
### remoteTrackStarted
Fired when any remote participant shares their mic, camera, or screen.
```javascript
meeting.on("remoteTrackStarted", function(remoteTrackItem) { });
```
Callback data (`remoteTrackItem`):
| Field | Type | Description |
|---|---|---|
| streamId | string | Unique stream identifier |
| type | string | `"audio"` or `"video"` |
| participantSessionId | string | Source participant's session ID |
| track | MediaStreamTrack | The media track (wrap in `new MediaStream([track])` for HTML video) |
| name | string | Source participant's display name |
| isComposedStream | boolean | `true` if this is a composed stream |
### remoteTrackStopped
Fired when a remote participant stops sharing mic, camera, or screen.
```javascript
meeting.on("remoteTrackStopped", function(remoteTrackItem) { });
```
Callback data: same shape as `remoteTrackStarted`.
### participantJoined
Fired to all existing participants when a new participant joins.
```javascript
meeting.on("participantJoined", function(participantInfo) { });
```
Callback data (`participantInfo`):
| Field | Type | Description |
|---|---|---|
| _id | string | participantSessionId |
| name | string | Display name |
| isAdmin | boolean | Whether participant is admin |
| meetingSessionId | string | Current meeting session ID |
| roomId | string | Room ID |
| email | string | Email if specified |
| externalUserId | string | External user ID if specified |
| meta | string | Custom metadata if specified |
### participantLeft
Fired to all other participants when someone leaves the meeting.
```javascript
meeting.on("participantLeft", function(participantInfo) { });
```
Callback data: same shape as `participantJoined`.
### onlineParticipants
Fired periodically during the meeting with the current list of online participants.
```javascript
meeting.on("onlineParticipants", function(onlineParticipants) { });
```
Callback data: Array of `{ _id, name, isAdmin, meetingSessionId, roomId }`
### stateChanged
Fired when the meeting connection state changes.
```javascript
meeting.on("stateChanged", function(meetingState) { });
```
`meetingState` values:
- `"not_joined"` - initial or error during join
- `"joining"` - join() called
- `"connecting_streams"` - connected to server, receiving streams
- `"joined"` - fully connected
- `"reconnect_success"` - reconnected after interruption
- `"network_connection_lost"` - connection interrupted
- `"network_connection_restored"` - connection restored
- `"terminated"` - meeting ended
### meetingEnded
Fired when the meeting is terminated (duration limit reached, admin ejected participant, room expired with ejectOnExpiry).
```javascript
meeting.on("meetingEnded", function() { });
```
Callback data: none.
### meetingLeft
Fired to the local participant after calling `leaveMeeting()`. Not emitted to other participants.
```javascript
meeting.on("meetingLeft", function() { });
```
Callback data: none.
### activeSpeaker
Fired when a participant is speaking.
```javascript
meeting.on("activeSpeaker", function(speakerInfo) { });
```
Callback data (`speakerInfo`):
| Field | Type | Description |
|---|---|---|
| streamId | string | Stream ID |
| meetingSessionId | string | Meeting session ID |
| name | string | Speaker's display name |
| roomId | string | Room ID |
| participantSessionId | string | Speaker's participant session ID |
| volumeLevel | number | -128 (silent) to 0 (loudest) |
### composedTrackStarted
Fired when a composed media stream is received (requires composition enabled on the room).
```javascript
meeting.on("composedTrackStarted", function(remoteTrackItem) { });
```
Callback data: same shape as `remoteTrackStarted` with `isComposedStream: true`.
---
### chatMessageReceived
Fired when a chat message arrives (a broadcast, or a directed message you sent or received).
```javascript
meeting.on("chatMessageReceived", function(msg) { });
```
| Field | Type | Description |
|---|---|---|
| _id | string | Message id |
| senderParticipantSessionId | string | Sender's participant session id |
| senderName | string | Sender display name |
| recipientParticipantSessionId | string | Present only on a directed (private) message |
| type | string | "text", "file", or "image" |
| content | string | Text, or the file name for file/image messages |
| fileName / fileMimeType / fileSizeBytes | | Present on file/image messages |
| downloadToken | string | Present on file/image messages; download via `GET /api/v1/chat/file/<_id>?dl=` |
| created | string | ISO timestamp |
| meetingSessionId | string | Present only on broadcast messages, not on directed (private) ones |
### chatHistory
Fired in response to `getChatHistory()`.
| Field | Type | Description |
|---|---|---|
| chatRoomId | string | Chat room id (or null) |
| before | string | The requested cursor (or null) |
| messages | array | Message objects (same shape as `chatMessageReceived`), oldest first |
| historyEnabled | boolean | false when the room stores no history; `messages` then come from the in-session buffer |
### chatTyping
Fired when a participant is typing (throttled ~1/2s). Broadcast to the whole meeting including the sender — filter on `participantSessionId` to ignore your own.
| Field | Type | Description |
|---|---|---|
| participantSessionId | string | The typing participant |
| senderName | string | Their display name |
| meetingSessionId | string | Meeting session id |
### chatMessageError
Fired when a chat action is rejected.
| Field | Type | Description |
|---|---|---|
| context | string | Which action failed (e.g. "sendChatMessage", "getChatHistory") |
| message | string | Reason (rate limit, chat disabled, recipient offline, invalid file reference, ...) |
## REST API
Base URL: `https://.metered.live/api/v1`
Auth: `?secretKey=` on every request.
Content-Type for POST/PUT bodies: `application/json`
---
### Room Endpoints
#### POST /room -- Create Room
Create a new meeting room.
```
POST https://.metered.live/api/v1/room?secretKey=
Content-Type: application/json
```
Request body:
| Field | Type | Required | Description |
|---|---|---|---|
| roomName | string | no | URL-friendly name; auto-generated if omitted |
| privacy | string | yes | `"public"` or `"private"` |
| expireUnixSec | integer | no | Room expiry (unix seconds) |
| ejectAtRoomExp | boolean | no | Eject participants at expiry |
| notBeforeUnixSec | integer | no | Earliest join time (unix seconds) |
| maxParticipants | integer | no | Max participants allowed |
| autoJoin | boolean | no | Auto join |
| enableRequestToJoin | boolean | no | Allow request-to-join for private rooms |
| enableChat | boolean | no | Enable in-meeting chat (prebuilt UI and SDK chat methods) |
| enableScreenSharing | boolean | no | Enable screen sharing (iframe only) |
| joinVideoOn | boolean | no | Camera on by default (iframe only) |
| joinAudioOn | boolean | no | Mic on by default (iframe only) |
| ownerOnlyBroadcast | boolean | no | Only admin can share media |
| enableRecording | boolean | no | Allow recording |
| recordRoom | boolean | no | Auto-record the meeting |
| ejectAfterElapsedTimeInSec | integer | no | Max participant duration (seconds) |
| meetingJoinWebhook | string | no | Webhook URL for join events |
| meetingLeftWebhook | string | no | Webhook URL for leave events |
| meetingStartedWebhook | string | no | Webhook URL for session start |
| meetingEndedWebhook | string | no | Webhook URL for session end |
| endMeetingAfterNoActivityInSec | integer | no | Auto-end after inactivity (seconds) |
| audioOnlyRoom | boolean | no | Audio-only room (audio pricing) |
| enableComposition | boolean | no | Enable composition (required for live streaming, recording composed, RTMP out) |
| compositionLayout | string | no | `"grid"` or `"active_speaker"` |
| recordComposition | boolean | no | Record the composed stream |
| enableRTMPOut | boolean | no | Stream to third-party RTMP services |
| rtmpOutURL | string | conditional | RTMP ingest URL (required when enableRTMPOut is true) |
| enableLiveStreaming | boolean | no | Enable HLS live streaming |
| showInviteBox | boolean | no | Show invite box (iframe only) |
| newChatForMeetingSession | boolean | no | Start a new chat per meeting session; false carries history across meetings in the room |
| chatHistoryRetentionHours | number | no | How long chat messages are kept, in hours (0-24). 0 (default) = delivered but never stored. Attachments are always removed after 24h |
| deleteOnExp | boolean | no | Delete room when it expires |
Response 200:
```json
{
"_id": "string",
"roomName": "string",
"privacy": "public",
"app": "string",
"created": "ISO date",
"deleteOnExp": false,
"autoJoin": false,
"enableRequestToJoin": false,
"enableChat": false,
"enableScreenSharing": true,
"joinVideoOn": true,
"joinAudioOn": true,
"ownerOnlyBroadcast": false,
"recordRoom": false,
"ejectAtRoomExp": false,
"archived": false,
"lang": "en"
}
```
#### GET /room/{roomName} -- Get Room
```
GET https://.metered.live/api/v1/room/{roomName}?secretKey=
```
Response 200: Room object (same shape as create response).
#### GET /rooms -- Get All Rooms
```
GET https://.metered.live/api/v1/rooms?secretKey=
```
Response 200: Paginated list.
```json
{
"pages": 4,
"limit": 10,
"skip": 0,
"data": [ { ...room with participantSessions... } ]
}
```
#### PUT /room/{roomName} -- Update Room
```
PUT https://.metered.live/api/v1/room/{roomName}?secretKey=
Content-Type: application/json
```
Request body: same fields as Create Room. All are optional except `privacy`.
Response 200: Updated room object.
#### DELETE /room/{roomName} -- Delete Room
```
DELETE https://.metered.live/api/v1/room/{roomName}?secretKey=
```
Response 200:
```json
{ "success": true, "message": "Room successfully archived" }
```
---
### Token Endpoints
#### POST /token -- Generate Access Token
Generate a token for joining private rooms or assigning identity.
```
POST https://.metered.live/api/v1/token?secretKey=
Content-Type: application/json
```
Request body:
| Field | Type | Required | Description |
|---|---|---|---|
| isAdmin | boolean | no | Grant admin privileges |
| roomName | string | no | Restrict token to specific room |
| globalToken | boolean | no | Token valid for all rooms |
| name | string | no | Participant display name |
| email | string | no | Participant email |
| meta | string | no | Custom metadata |
| externalUserId | string | no | Your system's user ID |
| expireUnixSec | integer | no | Token expiry (unix seconds) |
| notBeforeUnixSec | integer | no | Token not valid before (unix seconds) |
| ejectAfterElapsedTimeInSec | integer | no | Auto-eject after N seconds |
| joinVideoOn | boolean | no | Camera on by default (iframe) |
| joinAudioOn | boolean | no | Mic on by default (iframe) |
| disableVideo | boolean | no | Disable video (iframe) |
| disableAudio | boolean | no | Disable audio (iframe) |
| disableScreenSharing | boolean | no | Disable screen sharing (iframe) |
Response 200:
```json
{ "token": "" }
```
#### POST /token/validate -- Validate Token
**Note:** This endpoint does NOT require the `secretKey` query parameter.
```
POST https://.metered.live/api/v1/token/validate
Content-Type: application/json
```
Request body:
| Field | Type | Required |
|---|---|---|
| token | string | yes |
Response 200:
```json
{ "name": "James Bond" }
```
---
### Meeting Session Endpoints
#### GET /rooms/active/meetingsessions -- Get Active Sessions
```
GET https://.metered.live/api/v1/rooms/active/meetingsessions?secretKey=
```
Response 200: Array of active meeting sessions with embedded room objects.
```json
[{
"_id": "string",
"app": "string",
"room": { ...room object... },
"startTime": 1627654459,
"state": "active"
}]
```
#### GET /room/{roomName}/meetingsessions -- Get All Sessions for Room
```
GET https://.metered.live/api/v1/room/{roomName}/meetingsessions?secretKey=
```
Response 200: Paginated.
```json
{
"pages": 4,
"limit": 10,
"skip": 0,
"data": [{
"_id": "string",
"app": "string",
"room": "string",
"startTime": 1627598254,
"state": "ended",
"endTime": 1627598896,
"participantSessions": [{
"_id": "string",
"name": "string",
"joinTime": 1627598934,
"leftTime": 1627599054,
"state": "exited",
"browser": "Chrome",
"os": "Windows",
"isAdmin": false,
"authenticatedUsingToken": true,
"externalUserId": "string",
"email": "string"
}]
}]
}
```
#### GET /room/{roomName}/presence -- Get Meeting Presence
Get the current live presence for a room (active sessions with participants).
```
GET https://.metered.live/api/v1/room/{roomName}/presence?secretKey=
```
Response 200: Array of active sessions with room details (same shape as active sessions).
---
### Recording Endpoints
#### GET /recordings -- Get All Recordings
```
GET https://.metered.live/api/v1/recordings?secretKey=
```
Response 200:
```json
{
"currEndId": "string",
"total": 139,
"limit": 50,
"data": [{
"_id": "string",
"app": "string",
"room": "string",
"participantSession": "string",
"meetingSession": "string",
"participantUsername": "string",
"fileName": "uuid.webm",
"sizeInBytes": 4526446,
"type": "video",
"startTime": 1636847920,
"endTime": 1636847953
}]
}
```
#### GET /recordings/room/{roomName} -- Get Recordings for a Room
```
GET https://.metered.live/api/v1/recordings/room/{roomName}?secretKey=
```
Response 200: Same paginated recording structure.
#### GET /recordings/meetingsession/{meetingSessionId} -- Get Recordings for a Meeting Session
```
GET https://.metered.live/api/v1/recordings/meetingsession/{meetingSessionId}?secretKey=
```
Response 200: Same paginated recording structure.
#### GET /recordings/participantsession/{participantSessionId} -- Get Recordings for a Participant Session
```
GET https://.metered.live/api/v1/recordings/participantsession/{participantSessionId}?secretKey=
```
Response 200: Same paginated recording structure.
#### GET /recording/{recordingId}/download -- Download Recording
Returns a pre-signed S3 URL for downloading.
```
GET https://.metered.live/api/v1/recording/{recordingId}/download?secretKey=
```
Response 200:
```json
{ "url": "https://metered-recording.s3...presigned-url" }
```
#### DELETE /recording/{recordingId} -- Delete Recording
```
DELETE https://.metered.live/api/v1/recording/{recordingId}?secretKey=
```
Response 200:
```json
{ "success": true, "recordingId": "string", "message": "recording deleted successfully" }
```
---
### Live Streaming (Real-Time) Endpoints
These endpoints manage dedicated real-time live streaming rooms (separate from meeting rooms).
#### POST /realtimelivestreaming/room -- Create Live Streaming Room
```
POST https://.metered.live/api/v1/realtimelivestreaming/room?secretKey=
Content-Type: application/json
```
Request body:
| Field | Type | Required | Description |
|---|---|---|---|
| roomName | string | no | Auto-generated if omitted |
| enableLiveStreaming | boolean | no | Enable HLS streaming |
| displayMessage | string | no | Message when stream is offline |
| customCSS | string | no | Custom CSS for viewer |
| enableRecording | boolean | no | Record the livestream |
| recordComposition | boolean | no | Record composed audio+video |
| enableRTMPOut | boolean | no | Enable RTMP out |
| rtmpOutURL | string | no | Third-party RTMP ingest URL |
Response 200:
```json
{
"_id": "string",
"roomName": "mystreamingroom",
"viewerURL": "https://.metered.live//player",
"broadcastManager": "https://dashboard.metered.ca/livestreaming-rooms//app//broadcast",
"currentlyBroadcasting": false,
"created": "ISO date"
}
```
#### PUT /realtimelivestreaming/room/{roomName} -- Update Live Streaming Room
```
PUT https://.metered.live/api/v1/realtimelivestreaming/room/{roomName}?secretKey=
Content-Type: application/json
```
Request body: same fields as create. Response: same shape.
#### GET /realtimelivestreaming/rooms -- Get All Live Streaming Rooms
```
GET https://.metered.live/api/v1/realtimelivestreaming/rooms?secretKey=
```
Response 200: Array of live streaming room objects.
#### GET /realtimelivestreaming/room/{roomName} -- Get Live Streaming Room
```
GET https://.metered.live/api/v1/realtimelivestreaming/room/{roomName}?secretKey=
```
Response 200: Single live streaming room object.
#### GET /realtimelivestreaming/rooms/broadcasting -- Currently Broadcasting Rooms
```
GET https://.metered.live/api/v1/realtimelivestreaming/rooms/broadcasting?secretKey=
```
Response 200: Array of rooms with `currentlyBroadcasting: true`.
---
## Recording
Two recording modes:
1. Individual recording: records each participant's audio and video as separate files. Enable with `recordRoom: true` when creating/updating a room.
2. Composed recording: records all participants combined into a single video/audio file. Enable with `recordComposition: true` and `enableComposition: true` on the room.
Enable recording via Dashboard (room form > Recording & composition > Record individual streams; classic dashboard: Room settings > Record Room toggle) or via REST API (POST/PUT /room).
Manage recordings via:
- Dashboard: Video API & SDK > Cloud Recordings (Preview panel) for viewing, downloading, previewing, deleting (classic dashboard: Cloud Recording section).
- REST API: GET /recordings, GET /recordings/room/{roomName}, GET /recording/{id}/download, DELETE /recording/{id}.
Recording object shape:
```json
{
"_id": "string",
"app": "string",
"room": "string",
"participantSession": "string",
"meetingSession": "string",
"participantUsername": "string",
"fileName": "uuid.webm",
"sizeInBytes": 4526446,
"type": "video",
"startTime": 1636847920,
"endTime": 1636847953
}
```
---
## Live Streaming
Live streaming sends an HLS stream of the meeting that can be viewed by millions of users.
Requirements:
- Composition must be enabled (it is auto-enabled when live streaming is turned on).
- Enable via Dashboard (room form > Streaming output > HLS / DASH live streaming; classic dashboard: Room settings > HLS/Dash Live Streaming toggle) or via API (`enableLiveStreaming: true`).
Composition layouts: `grid`, `active_speaker`.
HLS playback URL format:
```
https://live.metered.ca/hls/{PLAYBACK_ID}.m3u8
```
The HLS URL is visible in Dashboard under Room summary once live streaming is enabled.
Playing the stream in a browser (using hls.js):
```html
```
iOS (AVPlayer) and Android (ExoPlayer) support HLS natively.
Receiving composed streams in the SDK: set `receiveVideoStreamType: "only_composed"` or `"all"` in `join()` options, then listen for the `composedTrackStarted` event.
---
## Composition
Composition combines multiple participant audio/video streams into a single composed stream.
Use cases:
- Live streaming (required)
- Composed recording (single video file of the whole meeting)
- RTMP OUT to third-party services
- Low-bandwidth participants (receive one stream instead of N)
Enable via:
- Dashboard: room form > Recording & composition > Enable composition (classic dashboard: Room settings > Composition toggle)
- API: `enableComposition: true` on create/update room
Layouts: `grid` (default), `active_speaker`
Set layout via API: `compositionLayout: "grid"` or `"active_speaker"`
SDK integration: when joining a room with composition enabled, use `receiveVideoStreamType` / `receiveAudioStreamType` set to `"only_composed"` or `"all"` in the `join()` options. The composed stream arrives via the `composedTrackStarted` event (or `remoteTrackStarted` with `isComposedStream: true`).
---
## RTMP OUT
RTMP OUT sends the composed meeting stream to third-party RTMP services (YouTube Live, Facebook Live, Twitch, etc.).
Requirements:
- Composition is auto-enabled when RTMP OUT is turned on.
- An RTMP ingest URL from the third-party service.
Enable via:
- Dashboard: room form > Streaming output > Push to external RTMP destination, then enter the RTMP OUT URL (classic dashboard: Room settings > Enable RTMP OUT).
- API: set `enableRTMPOut: true` and `rtmpOutURL: "rtmp://..."` when creating/updating a room.
The meeting will be streamed to the RTMP URL whenever participants are in the room with composition active.
---
## Webhooks
Rooms support four webhook URLs set via create/update room API:
| Field | Trigger |
|---|---|
| meetingJoinWebhook | Participant joins the room |
| meetingLeftWebhook | Participant leaves the room |
| meetingStartedWebhook | A new meeting session starts |
| meetingEndedWebhook | A meeting session ends |
---
## Error Responses
All REST endpoints return errors in this format:
```json
{ "success": false, "message": "error description" }
```
Common HTTP status codes: 200 (success), 400 (bad request), 500 (server error).
---
## Complete Quick-Start Example (HTML)
This is a minimal but complete working example that creates a two-person video call:
```html
Metered Quick Start
Metered Video Demo
Local Video
Remote Videos
```
---
## Device Selection Pattern
List available devices and let the user choose before or during a call:
```javascript
// List cameras
const cameras = await meeting.listVideoInputDevices();
// cameras = [{ deviceId: "abc123", groupId: "grp1", label: "Built-in Camera" }, ...]
// List microphones
const mics = await meeting.listAudioInputDevices();
// List speakers (not supported in Firefox)
const speakers = await meeting.listAudioOutputDevices();
// Select a specific camera (can be called before or after join)
await meeting.chooseVideoInputDevice(cameras[1].deviceId);
// Select a specific microphone
await meeting.chooseAudioInputDevice(mics[0].deviceId);
// Select a specific speaker
await meeting.chooseAudioOutputDevice(speakers[0].deviceId);
// After selecting, start sharing
await meeting.startVideo();
await meeting.startAudio();
```
Note: In Firefox, the `label` property may be blank if the user has not checked
"Remember this decision" when granting permissions.
---
## Custom Video Track Pattern (Canvas, Processed Video)
Share a canvas element or processed video stream instead of a camera:
```javascript
// Example: Share a canvas as video
const canvas = document.getElementById('myCanvas');
const canvasStream = canvas.captureStream(30); // 30 FPS
const videoTrack = canvasStream.getVideoTracks()[0];
await meeting.shareCustomVideoTrack(videoTrack);
// Example: Apply a filter to camera using canvas
const localStream = await meeting.getLocalVideoStream();
const videoEl = document.createElement('video');
videoEl.srcObject = localStream;
await videoEl.play();
const canvas2 = document.createElement('canvas');
const ctx = canvas2.getContext('2d');
function drawFrame() {
ctx.drawImage(videoEl, 0, 0);
// Apply any canvas manipulations here (filters, overlays, etc.)
ctx.filter = 'grayscale(100%)';
ctx.drawImage(videoEl, 0, 0);
requestAnimationFrame(drawFrame);
}
drawFrame();
const processedStream = canvas2.captureStream(30);
const processedTrack = processedStream.getVideoTracks()[0];
await meeting.shareCustomVideoTrack(processedTrack);
```
---
## Custom Audio Pattern (Web Audio API)
Share processed audio or synthesized audio instead of a microphone:
```javascript
const audioContext = new AudioContext();
// Example: Mix microphone with background audio
const micStream = await navigator.mediaDevices.getUserMedia({ audio: true });
const micSource = audioContext.createMediaStreamSource(micStream);
const destination = audioContext.createMediaStreamDestination();
// Add gain control
const gainNode = audioContext.createGain();
gainNode.gain.value = 0.8;
micSource.connect(gainNode);
gainNode.connect(destination);
// Share the processed audio
await meeting.shareCustomAudio(destination.stream);
```
---
## Private Rooms and Authentication Flow
1. Create a private room:
```
POST /api/v1/room?secretKey=
{ "roomName": "secure-room", "privacy": "private" }
```
2. Generate an access token for each user (server-side):
```
POST /api/v1/token?secretKey=
{
"roomName": "secure-room",
"name": "Alice",
"isAdmin": false,
"email": "alice@example.com",
"externalUserId": "user-123",
"ejectAfterElapsedTimeInSec": 3600
}
```
Response: `{ "token": "" }`
3. Client joins with the token:
```javascript
const meetingInfo = await meeting.join({
roomURL: "yourapp.metered.live/secure-room",
name: "Alice",
accessToken: ""
});
```
4. Validate a token (optional, server-side):
```
POST /api/v1/token/validate
{ "token": "" }
```
Response: `{ "name": "Alice" }`
Admin users can:
- Allow other users without tokens to join private meetings (request-to-join flow)
- Be the only ones who can broadcast (if `ownerOnlyBroadcast` is enabled on the room)
---
## REST API cURL Examples
Create a room:
```bash
curl -X POST \
'https://yourapp.metered.live/api/v1/room?secretKey=YOUR_SECRET_KEY' \
-H 'Content-Type: application/json' \
-d '{
"roomName": "my-meeting",
"privacy": "public",
"enableRecording": true,
"ejectAfterElapsedTimeInSec": 7200
}'
```
Get a room:
```bash
curl -X GET \
'https://yourapp.metered.live/api/v1/room/my-meeting?secretKey=YOUR_SECRET_KEY' \
-H 'Accept: application/json'
```
Update a room:
```bash
curl -X PUT \
'https://yourapp.metered.live/api/v1/room/my-meeting?secretKey=YOUR_SECRET_KEY' \
-H 'Content-Type: application/json' \
-d '{
"enableComposition": true,
"compositionLayout": "active_speaker",
"enableLiveStreaming": true,
"enableRTMPOut": true,
"rtmpOutURL": "rtmp://a.rtmp.youtube.com/live2/your-stream-key"
}'
```
Delete a room:
```bash
curl -X DELETE \
'https://yourapp.metered.live/api/v1/room/my-meeting?secretKey=YOUR_SECRET_KEY' \
-H 'Accept: application/json'
```
Generate access token:
```bash
curl -X POST \
'https://yourapp.metered.live/api/v1/token?secretKey=YOUR_SECRET_KEY' \
-H 'Content-Type: application/json' \
-d '{
"roomName": "my-meeting",
"name": "John Doe",
"isAdmin": true,
"externalUserId": "user-456",
"ejectAfterElapsedTimeInSec": 1800
}'
```
Get all recordings:
```bash
curl -X GET \
'https://yourapp.metered.live/api/v1/recordings?secretKey=YOUR_SECRET_KEY' \
-H 'Accept: application/json'
```
Download a recording:
```bash
curl -X GET \
'https://yourapp.metered.live/api/v1/recording/RECORDING_ID/download?secretKey=YOUR_SECRET_KEY' \
-H 'Accept: application/json'
```
Get active meeting sessions:
```bash
curl -X GET \
'https://yourapp.metered.live/api/v1/rooms/active/meetingsessions?secretKey=YOUR_SECRET_KEY' \
-H 'Accept: application/json'
```
Create a live streaming room:
```bash
curl -X POST \
'https://yourapp.metered.live/api/v1/realtimelivestreaming/room?secretKey=YOUR_SECRET_KEY' \
-H 'Content-Type: application/json' \
-d '{ "roomName": "my-livestream" }'
```
---
## Room Configuration Reference
These fields control room behavior and can be set via POST /room or PUT /room/{roomName}:
Core settings:
- `roomName` (string): URL-friendly room name; auto-generated if omitted.
- `privacy` ("public"|"private"): Public rooms are open; private rooms require an access token.
- `maxParticipants` (integer): Cap on concurrent participants.
- `expireUnixSec` (integer): Room expiry time in unix seconds.
- `notBeforeUnixSec` (integer): Earliest time users can join.
- `ejectAtRoomExp` (boolean): Kick everyone when room expires.
- `ejectAfterElapsedTimeInSec` (integer): Max time per participant in seconds.
- `endMeetingAfterNoActivityInSec` (integer): Auto-end if no one is sharing media.
- `audioOnlyRoom` (boolean): Restrict to audio-only (different pricing tier).
Media defaults (iframe only):
- `joinVideoOn` (boolean): Camera on when joining.
- `joinAudioOn` (boolean): Mic on when joining.
- `enableScreenSharing` (boolean): Allow screen sharing.
- `enableChat` (boolean): Enable text chat.
- `ownerOnlyBroadcast` (boolean): Only admins can share media.
- `autoJoin` (boolean): Auto-join without lobby.
- `enableRequestToJoin` (boolean): Allow non-token users to request joining private rooms.
- `newChatForMeetingSession` (boolean): Fresh chat per session.
- `showInviteBox` (boolean): Show invite UI when room is empty.
Recording:
- `enableRecording` (boolean): Allow manual recording.
- `recordRoom` (boolean): Auto-record every session.
- `recordComposition` (boolean): Record the composed (combined) stream.
Composition and streaming:
- `enableComposition` (boolean): Combine all streams into one. Required for live streaming and RTMP out.
- `compositionLayout` ("grid"|"active_speaker"): Layout for composed stream.
- `enableLiveStreaming` (boolean): Generate HLS URL for the meeting.
- `enableRTMPOut` (boolean): Push composed stream to RTMP endpoint.
- `rtmpOutURL` (string): RTMP ingest URL (e.g., YouTube Live, Twitch).
Webhooks:
- `meetingJoinWebhook` (string): URL called when a participant joins.
- `meetingLeftWebhook` (string): URL called when a participant leaves.
- `meetingStartedWebhook` (string): URL called when a meeting session starts.
- `meetingEndedWebhook` (string): URL called when a meeting session ends.
---
## Meeting State Lifecycle
```
not_joined -> joining -> connecting_streams -> joined
|
v
network_connection_lost
|
v
network_connection_restored
|
v
reconnect_success -> joined
joined -> terminated (when meetingEnded fires)
joined -> not_joined (when leaveMeeting() called)
```
States:
- `not_joined`: Initial state or failed to join.
- `joining`: join() has been called, connecting to server.
- `connecting_streams`: Connected, receiving initial media streams.
- `joined`: Fully connected and operational.
- `network_connection_lost`: Network interruption detected.
- `network_connection_restored`: Network back, reconnecting.
- `reconnect_success`: Successfully reconnected.
- `terminated`: Meeting ended externally (admin eject, room expiry, duration limit).
---
## Live Streaming Playback Reference
HLS URL format: `https://live.metered.ca/hls/{PLAYBACK_ID}.m3u8`
The PLAYBACK_ID / HLS URL is available from the room details in the Metered dashboard
after enabling live streaming.
Browser playback with hls.js:
```html
```
React playback:
```jsx
import React, { useEffect, useRef } from "react";
import Hls from "hls.js";
export default function LivePlayer() {
const videoRef = useRef(null);
const src = "https://live.metered.ca/hls/PLAYBACK_ID.m3u8";
useEffect(() => {
let hls;
if (videoRef.current) {
const video = videoRef.current;
if (video.canPlayType("application/vnd.apple.mpegurl")) {
video.src = src;
} else if (Hls.isSupported()) {
hls = new Hls();
hls.loadSource(src);
hls.attachMedia(video);
}
}
return () => { if (hls) hls.destroy(); };
}, [videoRef]);
return ;
}
```
Android (ExoPlayer):
```java
SimpleExoPlayer player = new SimpleExoPlayer.Builder(context).build();
player.setMediaItem(MediaItem.fromUri("https://live.metered.ca/hls/PLAYBACK_ID.m3u8"));
player.prepare();
```
iOS/tvOS (AVPlayer):
```swift
import AVKit
let player = AVPlayer(url: URL(string: "https://live.metered.ca/hls/PLAYBACK_ID.m3u8")!)
// Use with AVPlayerViewController or AVPlayerLayer
player.play()
```
Recommended players for web: hls.js (free), Plyr.io (free), JWPlayer, Brightcove, THEOplayer, Bitmovin.
---
## RTMP OUT Setup Examples
YouTube Live:
1. Go to YouTube Studio > Go Live > Stream
2. Copy the Stream URL and Stream Key
3. Combine them: `rtmp://a.rtmp.youtube.com/live2/YOUR_STREAM_KEY`
4. Set on room: `enableRTMPOut: true, rtmpOutURL: "rtmp://a.rtmp.youtube.com/live2/YOUR_STREAM_KEY"`
Facebook Live:
1. Go to Facebook Live Producer
2. Copy the Server URL and Stream Key
3. Set on room: `rtmpOutURL: "rtmps://live-api-s.facebook.com:443/rtmp/YOUR_STREAM_KEY"`
Twitch:
1. Go to Twitch Dashboard > Settings > Stream
2. Copy the Primary Stream Key
3. Set on room: `rtmpOutURL: "rtmp://live.twitch.tv/app/YOUR_STREAM_KEY"`
Other services: use the RTMP ingest URL provided by the service.
---
## Composed Stream Receiver Pattern
To receive and display only the composed (combined) stream instead of individual streams:
```javascript
const meeting = new Metered.Meeting();
await meeting.join({
roomURL: "yourapp.metered.live/composed-room",
name: "Viewer",
receiveVideoStreamType: "only_composed",
receiveAudioStreamType: "only_composed"
});
// The composed stream arrives via composedTrackStarted
meeting.on("composedTrackStarted", function(remoteTrackItem) {
var track = remoteTrackItem.track;
var stream = new MediaStream([track]);
if (remoteTrackItem.type === "video") {
document.getElementById("composedVideo").srcObject = stream;
}
if (remoteTrackItem.type === "audio") {
var audio = document.createElement("audio");
audio.autoplay = true;
audio.srcObject = stream;
document.body.append(audio);
}
});
```
Note: when `receiveAudioStreamType` is `"only_composed"` and the participant is also sharing
their own audio, they will hear their own voice in the composed stream.
To receive both individual and composed streams, use `receiveVideoStreamType: "all"`. Individual
streams arrive via `remoteTrackStarted` and composed streams arrive via `composedTrackStarted`
(or `remoteTrackStarted` with `isComposedStream: true`).
---
## Server-Side Room Management Pattern (Node.js)
```javascript
const axios = require('axios');
const BASE_URL = 'https://yourapp.metered.live/api/v1';
const SECRET_KEY = process.env.METERED_SECRET_KEY;
// Create a room
async function createRoom(roomName, isPrivate) {
const response = await axios.post(`${BASE_URL}/room`, {
roomName: roomName,
privacy: isPrivate ? 'private' : 'public',
ejectAfterElapsedTimeInSec: 7200,
enableRecording: true
}, {
params: { secretKey: SECRET_KEY }
});
return response.data;
}
// Generate token for a user
async function generateToken(roomName, userName, isAdmin) {
const response = await axios.post(`${BASE_URL}/token`, {
roomName: roomName,
name: userName,
isAdmin: isAdmin
}, {
params: { secretKey: SECRET_KEY }
});
return response.data.token;
}
// Get active sessions
async function getActiveSessions() {
const response = await axios.get(`${BASE_URL}/rooms/active/meetingsessions`, {
params: { secretKey: SECRET_KEY }
});
return response.data;
}
// Get recordings for a room
async function getRoomRecordings(roomName) {
const response = await axios.get(`${BASE_URL}/recordings/room/${roomName}`, {
params: { secretKey: SECRET_KEY }
});
return response.data;
}
// Download a recording
async function getRecordingDownloadURL(recordingId) {
const response = await axios.get(`${BASE_URL}/recording/${recordingId}/download`, {
params: { secretKey: SECRET_KEY }
});
return response.data.url;
}
```
---
## Part 2: TURN Server Service
# Metered TURN Server Service — llms.txt reference
Metered TURN Servers as a Service provide a globally distributed relay network for WebRTC traffic. The service guarantees connectivity through NATs and firewalls via TURN (Traversal Using Relays around NAT).
- 31+ regions, 100+ edge PoPs, <30 ms latency, 99.999% uptime SLA
- UDP, TCP, TLS, DTLS on ports 80/443. No bandwidth caps per allocation.
- Standards: STUN (RFC 5389), TURN (RFC 5766), ICE
- Private high-speed backbone for cross-continent relay
- REST API for credentials, usage tracking, project isolation
- Dashboard: https://dashboard.metered.ca | Pricing: https://www.metered.ca/pricing
## Getting Started
1. **Sign up** at https://dashboard.metered.ca/signup to create a free Metered account.
2. Your **app name** (e.g. `yourappname`) is shown on the Dashboard home page. It forms part of the REST API base URL: `https://yourappname.metered.live/api/v1/turn/`.
3. Go to **Dashboard → Developers** to find your **Secret Key**. Use this for all server-side API calls (creating credentials, fetching usage, managing projects). Never expose it in front-end code.
4. **Create a TURN credential**: Go to **Dashboard → TURN Server → Credentials** and click **Create Credential** (classic dashboard: **TURN Server** page → **Add Credential**), or use the Create Credential REST API. Each credential gets:
- `username` and `password` — used in the ICE server config for WebRTC connections
- `apiKey` — a credential-scoped key, **safe for front-end use**, used only with the Get Credential API to fetch the ICE server config
5. Click **Get credential → Show ICE Servers Array** on any credential (classic dashboard: the **Show ICE Servers Array** button on the row) to get a ready-to-use ICE config for your WebRTC app. The **ICE** button on a row copies the same array to the clipboard.
**Two dashboards.** Metered has a redesigned dashboard (https://dashboard.metered.ca/v2) and the classic dashboard; both manage the same account, and the API is identical. Users switch with the **Old dashboard** button (new → classic) or by opening /v2 (classic → new). Navigation map (new → classic):
- TURN Server → **Credentials** → *Create Credential* ↔ TURN Server page → *Add Credential*
- Credentials row → **Get credential** → *Show ICE Servers Array* / *Show API Key* / *Delete credential* ↔ row buttons *Show ICE Servers Array* / *Show API Key* / *Remove*
- Credentials row → **ICE** button copies the ICE servers array to the clipboard (no classic equivalent)
- Credentials page → **TURN region** card (new: also a per-credential *Region* in Create Credential) ↔ TURN Server page → *Default TURN Server Region* dropdown
- TURN Server → **Projects** → *New project* / card *Edit* / *Manage* ↔ Projects section on the TURN Server page → *Create Project* / *Edit Project* / *Manage TURN Credentials*
- TURN Server → **Analytics** (new only), **Emergency support** page ↔ Emergency Phone Support panel on the TURN Server page
- **Developers** → *Reveal* / *Reissue it* ↔ Developers → secret key shown / *Regenerate Secret Key*
- **Plans & pricing** page, *Manage subscription* ↔ plan cards at the bottom of the TURN Server page
- Account → **Billing** → *Auto-reload* / *Add Funds* / *Usage History* / *Payment History*; Account → **Team**; Account → **Branding** ↔ Account → *Automatic Billing* / *Add Funds* / *Usage History* / *Payment History* / *Members* / *Custom Branding*
**Three types of API keys:**
- **`secretKey`** — account-scoped, server-side only. Found in Dashboard → Developers.
- **`apiKey`** — credential-scoped, safe for front-end. Returned when creating a credential. Used only for the Get Credential endpoint.
- **`projectApiKey`** — project-scoped, alternative to secretKey for project-level operations. Found in Dashboard → TURN Server → Projects.
---
## Overview & Setup
ICE tries connections in order: host candidates (direct), STUN (public IP discovery), then TURN (full relay fallback). TURN guarantees connectivity through symmetric NAT, carrier-grade NAT, and strict firewalls. The relay forwards encrypted payloads (SRTP/DTLS) without decrypting them.
Use cases: voice/video calls, live streaming, IoT devices, AI/3D/AR/VR, surveillance, DataChannels (chat, gaming, file-share).
### Custom Domain
Point a CNAME at Metered infrastructure (global or region-specific hostname). TURN over TCP and UDP work with CNAME; TURN over TLS does not.
---
## TURN URLs & Ports
### Global Endpoint (recommended)
`global.relay.metered.ca` — automatic geo-routing to nearest edge. STUN: `stun:stun.relay.metered.ca:80`
| Port | Protocol | URI |
|------|----------|--------------------------------------------------|
| 80 | UDP | turn:global.relay.metered.ca:80 |
| 80 | TCP | turn:global.relay.metered.ca:80?transport=tcp |
| 443 | UDP | turn:global.relay.metered.ca:443 |
| 443 | TLS | turns:global.relay.metered.ca:443?transport=tcp |
Best practice: include multiple entries (UDP first, then TCP/TLS) for ICE fallback.
### Recommended ICE Servers Array
```json
[
{ "urls": "stun:stun.relay.metered.ca:80" },
{ "urls": "turn:global.relay.metered.ca:80", "username": "", "credential": "" },
{ "urls": "turn:global.relay.metered.ca:80?transport=tcp", "username": "", "credential": "" },
{ "urls": "turn:global.relay.metered.ca:443", "username": "", "credential": "" },
{ "urls": "turns:global.relay.metered.ca:443?transport=tcp", "username": "", "credential": "" }
]
```
### Region-Specific Endpoints
All use ports 80/443. Paid plans only (free plan: `standard.relay.metered.ca` only).
| Region | Endpoint | API region value |
|------------------|--------------------------------|---------------------|
| Global | global.relay.metered.ca | global |
| North America | na.relay.metered.ca | north_america |
| Europe | europe.relay.metered.ca | europe |
| European Union | eu.relay.metered.ca | eu |
| Asia | asia.relay.metered.ca | asia |
| Oceania | oceania.relay.metered.ca | oceania |
| US West | us-west.relay.metered.ca | us_west |
| US Central | us-central.relay.metered.ca | us_central |
| US East | us-east.relay.metered.ca | us_east |
| Canada Central | ca-central.relay.metered.ca | canada_central |
| Canada East | ca-east.relay.metered.ca | canada_east |
| Europe West | eu-west.relay.metered.ca | europe_west |
| Europe Central | eu-central.relay.metered.ca | europe_central |
| Asia West | asia-west.relay.metered.ca | asia_west |
| Asia East | asia-east.relay.metered.ca | asia_east |
| Middle East | middle-east.relay.metered.ca | middle_east |
| Canada | ca.relay.metered.ca | canada |
| USA | us.relay.metered.ca | usa |
| UK | uk.relay.metered.ca | uk |
| Singapore | sg.relay.metered.ca | singapore |
| India | in.relay.metered.ca | india |
| Seoul | seoul.relay.metered.ca | seoul |
| France | fr.relay.metered.ca | france |
| Germany | de.relay.metered.ca | germany |
| Italy | it.relay.metered.ca | italy |
| Japan | jp.relay.metered.ca | japan |
| Sweden | se.relay.metered.ca | sweden |
| Spain | es.relay.metered.ca | spain |
| Netherlands | nl.relay.metered.ca | netherlands |
| Australia | au.relay.metered.ca | australia |
| Qatar | qa.relay.metered.ca | qatar |
| Standard (free) | standard.relay.metered.ca | standard |
---
## Creating Credentials
**Dashboard**: Log into https://dashboard.metered.ca -> TURN Server -> Credentials -> "Create Credential", then the row's "Get credential" -> "Show ICE Servers Array" to get the config (classic dashboard: TURN Server page -> "Add Credential" -> "Show ICE Servers Array").
**REST API**: POST to Create Credential endpoint (see below). Response includes `username`, `password`, and `apiKey`. Use the `apiKey` to call Get Credential from the front-end. The `apiKey` is credential-scoped and safe for front-end use. The `secretKey` must never be exposed in front-end code.
**Propagation delay**: a newly created credential is not usable immediately. It has to propagate across the global TURN network, which can take **up to 2 minutes**. Before it has propagated, an authenticated Allocate can be rejected and no relay candidate is gathered, even though the credential is valid. Never create a credential at call-setup time; create it ahead of time from the back-end and reuse it. See "Rotating Credentials" below.
---
## Region Pinning
**Dashboard**: Pick the region in the "TURN region" card on the Credentials page, or set a per-credential Region in "Create Credential" (classic dashboard: the "Default TURN Server Region" dropdown); "Show ICE Servers Array" then returns region-scoped endpoints.
**API**: Pass `region` query param to Get Credential API for a specific region. Omit it to use the credential's own region if it was pinned when created on the new dashboard (paid plans), otherwise the dashboard default. Different credentials can target different regions.
**Dynamic updates**: If you use the Get Credential API (with `apiKey`), changing the dashboard region automatically updates what the API returns (for credentials without their own pinned region).
---
## REST API — Authentication
Replace `` with your app name (Dashboard -> Developers).
**v1 endpoints** (base: `https://.metered.live/api/v1/turn/`):
Get Credential, Create Credential, Enable Credential, Disable Credential, Delete Credential, Current Usage, Current Usage by Date, Current Usage for User.
**v2 endpoints** (base: `https://.metered.live/api/v2/turn/`):
Update Credential Label, List Credentials, Current Usage by User, Daily Usage by User, Delete Credential by Label, all Project endpoints.
**v2 payment endpoint** (base: `https://.metered.live/api/v2/payment/`):
Get Usage Charges — note this uses `/api/v2/payment/`, NOT `/api/v2/turn/`.
Each endpoint below shows its full path including the correct version prefix.
Auth methods (all via query param):
1. `apiKey` — credential-scoped, safe for front-end. Only for Get Credential endpoint.
2. `secretKey` — account-scoped, server-side only. Dashboard -> Developers.
3. `projectApiKey` — project-scoped, alternative to secretKey for project endpoints.
---
## REST API — Credentials
### Get TURN Credential (ICE Servers Array)
Returns the ICE Servers array. Safe for front-end use.
```
GET /api/v1/turn/credentials?apiKey=
```
Query: `apiKey` (required), `region` (optional, overrides dashboard default).
Response `200 OK` — array of ICE server objects (STUN + TURN entries with urls, username, credential).
Errors: `400` (no API key), `401` (invalid API key).
### Create TURN Credential
```
POST /api/v1/turn/credential?secretKey=
Content-Type: application/json
```
Body (JSON):
- `expiryInSeconds` (integer, optional) — auto-expire after this many seconds
- `label` (string, optional) — a label for the credential
Response `200 OK` — object with `username`, `password`, `expiryInSeconds`, `label`, `apiKey`.
Errors: `400` (invalid expiry or not subscribed).
**Propagation delay**: a newly created credential is not usable immediately. It has to propagate across the global TURN network, which can take **up to 2 minutes**. Before it has propagated, an authenticated Allocate can be rejected and no relay candidate is gathered, even though the credential is valid. Never create a credential at call-setup time; create it ahead of time from the back-end and reuse it. See "Rotating Credentials" below.
### Enable TURN Credential
Re-enables a previously disabled credential.
```
POST /api/v1/turn/credential/enable?secretKey=
```
Body: `{ "username": "" }`
Response `200 OK`: `{ "message": "Credential enabled successfully" }`
Errors: `400` (missing username, already enabled), `401` (invalid key, not found).
### Disable TURN Credential
```
POST /api/v1/turn/credential/disable?secretKey=
```
Body: `{ "username": "" }`
Response `200 OK`: `{ "message": "Turn credential disabled successfully" }`
Errors: `400` (missing username, already disabled), `401` (not found).
### Delete TURN Credential
```
DELETE /api/v1/turn/credential?secretKey=
```
Body: `{ "username": "" }`
Response `200 OK`: `{ "success": true, "message": "credential removed" }`
Errors: `400` (credential not found).
### Update TURN Credential Label
```
POST /api/v2/turn/credential/update_label?secretKey=&username=
```
Body: `{ "label": "" }`
Response `200 OK` — object with `username`, `password`, `expiryInSeconds`, `label`, `apiKey`.
Errors: `400` (credential not found).
### List TURN Credentials (v2)
```
GET /api/v2/turn/credentials?secretKey=
```
Query params:
- `secretKey` (string, required)
- `all` (boolean, optional) — include expired credentials; default false
- `page` (integer, optional) — page number for pagination
- `label` (string, optional) — filter by label
Response `200 OK` — object with `data[]` and `pagination`.
Each credential in `data[]`: `username`, `password`, `apiKey`, `expiryInSeconds`, `label`, `expired` (bool).
`pagination`: `total_records`, `current_page`, `total_pages`, `next_page`, `prev_page`.
Errors: `400` (not subscribed, not available under free plan).
### Delete TURN Credential by Label
Deletes all active (non-expired) credentials matching a label.
```
DELETE /api/v2/turn/credential/by_label?secretKey=&label=