RelayrtcDocs
Get started
Documentation
Get started

Build your first call

Create a room, issue participant tokens and connect a React audio and video interface.

On this page

This guide connects two people to the same room. Your backend creates the room and issues a separate participant token for each caller. Your React application joins the room and lets each person enable their devices.

Requirements

  • A running RelayRTC deployment with API, signaling and media services reachable from your application.
  • A project environment and a secret API key with rooms:create and tokens:create.
  • Node.js 22 or newer on your backend and React 18.3.1 or 19 on your frontend.
  • The Node and React packages.

Use HTTPS for a deployed application; localhost is supported for development. Camera and microphone capture require browser permission.

Configure your server

Set these values in your backend environment. The example addresses match the default local deployment; use your deployment's public addresses for remote browsers.

Shell
RELAYRTC_API_URL=http://localhost:8080/v1
RELAYRTC_SECRET_KEY=your-environment-secret-api-key
RELAYRTC_SIGNALING_URL=ws://localhost:8081/v1/connect

The API URL is used by your server. The signaling URL must be reachable from participant browsers. Signaling must also allow your frontend's origin.

Create a room

Create relay.ts in your backend. This module exports the client used in the following server examples.

TypeScript
import { RelayServer } from '@relayrtc/node'
 
const apiUrl = process.env.RELAYRTC_API_URL
const apiKey = process.env.RELAYRTC_SECRET_KEY
if (!apiUrl || !apiKey) throw new Error('Configure the RelayRTC API URL and secret key')
 
export const relay = new RelayServer({ apiUrl, apiKey })

Create a room when your application creates a call, then save the returned ID in your application database.

TypeScript
import { relay } from './relay.js'
 
export async function createCall() {
  const room = await relay.rooms.create({ name: 'Team call', maxParticipants: 10 })
  return room.id
}

Everyone in that call uses the saved room.id. Do not create a new room for each participant.

Issue participant tokens

Create a backend helper for your join endpoint:

TypeScript
import { relay } from './relay.js'
 
export async function issueJoinToken(roomId: string, participantName: string) {
  const signalingUrl = process.env.RELAYRTC_SIGNALING_URL
  if (!signalingUrl) throw new Error('Configure the public signaling URL')
 
  const issued = await relay.tokens.create(roomId, {
    participantName,
    ttlSeconds: 3600,
    permissions: ['room:join', 'audio:publish', 'video:publish'],
  })
 
  return { token: issued.token, expiresAt: issued.expiresAt, signalingUrl }
}

This helper is server code, not an unrestricted HTTP endpoint. Your application implements the endpoint around it: authenticate the request, look up the call's saved room ID, check membership, and derive the participant name from your user record. Only then call issueJoinToken and return its result. Do not accept a caller-supplied permission array or let an arbitrary room ID bypass that check.

Issue a token separately for each participant. A token creates a participant identity; sharing it between callers is not a way to invite more people. See keys and permissions before adding screen sharing or messaging permissions.

Connect from React

Create Call.tsx in your frontend. Pass the result of your authenticated join endpoint as its props. In Next.js, keep this component behind the client boundary shown here.

React
'use client'
 
import { useState } from 'react'
import {
  MediaLoader, RelayProvider, RelayRoom, useLocalMedia,
  useLocalParticipant, useMediaTrack, useRoom, useTracks,
} from '@relayrtc/react'
import type { RoomRemoteTrack } from '@relayrtc/react'
 
function RemoteMedia({ track }: { track: RoomRemoteTrack }) {
  const media = useMediaTrack(track)
  const audio = track.type === 'audio' || track.type === 'screen_audio'
 
  return (
    <div>
      {audio
        ? <audio ref={media.ref} autoPlay />
        : <video ref={media.ref} autoPlay playsInline hidden={media.isPaused} />}
      {!audio && media.isPaused && <p>Camera paused</p>}
      {media.isLoading && <MediaLoader label="Connecting media" />}
      {media.state === 'blocked' && (
        <button onClick={() => void media.play().catch(() => undefined)}>Play media</button>
      )}
      {media.error && media.state !== 'blocked' && <p role="alert">{media.error.message}</p>}
    </div>
  )
}
 
function CallContent() {
  const local = useLocalParticipant()
  const { connectionState, error, leave } = useRoom()
  const { camera, microphone } = useLocalMedia()
  const preview = useMediaTrack(camera?.track, { paused: camera?.muted ?? false })
  const tracks = useTracks({ types: ['camera_video', 'audio'] })
  const [deviceError, setDeviceError] = useState<string | null>(null)
 
  async function run(action: () => Promise<void>) {
    setDeviceError(null)
    try { await action() }
    catch (cause) { setDeviceError(cause instanceof Error ? cause.message : 'Device operation failed') }
  }
 
  return (
    <section>
      <p role="status">{connectionState}</p>
      {error && <p role="alert">{error.message}</p>}
      {deviceError && <p role="alert">{deviceError}</p>}
      <video ref={preview.ref} autoPlay muted playsInline hidden={!camera?.enabled || camera.muted} />
      <button
        disabled={!local || camera?.pending || connectionState !== 'connected'}
        onClick={() => void run(async () => {
          if (!local) return
          if (camera?.enabled) await local.camera.disable()
          else await local.camera.enable()
        })}
      >{camera?.enabled ? 'Turn camera off' : 'Turn camera on'}</button>
      <button
        disabled={!local || microphone?.pending || connectionState !== 'connected'}
        onClick={() => void run(async () => {
          if (!local) return
          if (!microphone?.enabled) await local.microphone.enable()
          else if (microphone.muted) await local.microphone.unmute()
          else await local.microphone.mute()
        })}
      >{!microphone?.enabled ? 'Enable microphone' : microphone.muted ? 'Unmute' : 'Mute'}</button>
      <button onClick={() => void run(leave)}>Leave call</button>
      {tracks.map(track => <RemoteMedia key={track.id} track={track} />)}
    </section>
  )
}
 
export function Call({ token, signalingUrl }: { token: string; signalingUrl: string }) {
  return (
    <RelayProvider signalingUrl={signalingUrl} autoSubscribe>
      <RelayRoom token={token}><CallContent /></RelayRoom>
    </RelayProvider>
  )
}

Joining does not open capture devices. The camera and microphone buttons request permission from a user interaction. The local preview is muted to avoid feedback. RelayRoom manages the connection while mounted; useMediaTrack attaches and cleans up each media element.

Render remote video

RemoteMedia renders remote camera tracks as video. A published track, a subscribed track and a playing video are different stages. Keep the media element mounted while it loads. Paused tracks can show a placeholder; an unpublished camera disappears from useTracks.

Render remote audio

The same component renders microphone tracks in separate audio elements. Browsers may block autoplay with sound. The Play media button retries from a click when the hook reports blocked; another automatic retry is not a substitute for that user gesture.

Test with a second participant

Open your frontend in a second browser or browser profile and request a separate token for the same saved room. Enable media on both sides. Use headphones to avoid feedback.

Confirm that both interfaces reach connected, each participant sees the other's camera, and audio plays after any required playback click. If membership works but media does not, follow troubleshooting calls.

For longer calls, configure authorized token renewal. Then add screen sharing, messages, or audio-only roles.