RelayrtcDocs
Get started
Documentation
Build calls

Connection recovery

Keep call state visible during reconnects and renew credentials through your backend.

On this page

A network interruption, an expired participant token and an expired TURN credential require different recovery actions. Show the SDK's connection state and keep your media components mounted while automatic recovery is in progress.

Room state

Render this status component inside your room:

React
'use client'
 
import { MediaLoader, useRoom } from '@relayrtc/react'
 
export function ConnectionStatus() {
  const { connectionState, error } = useRoom()
  if (connectionState === 'reconnecting') return <MediaLoader label="Reconnecting to the call" />
  if (connectionState === 'failed') return <p role="alert">{error?.message ?? 'The call could not reconnect'}</p>
  return <p role="status">{connectionState}</p>
}

The default reconnect policy allows up to six attempts within 25 seconds. It attempts to restore the existing session and repair media transport. This does not guarantee recovery after the room ends, the participant is removed or the services lose the session's state.

Playback loading

useMediaTrack reports loading while a remote publication starts or its room reconnects. Keep the media element mounted so the hook can reattach it. A successful subscription is not proof that a decodable frame has arrived.

If recovery reaches a terminal failure, offer a deliberate rejoin action that asks your backend to authorize access again. Do not continuously issue new identities in a retry loop.

Participant token expiry

For longer meetings, configure refreshToken and use backend tokens.renew. This preserves the participant and session; tokens.create creates another identity instead.

Your backend should retain the current participant credential in a server-side record tied to the authenticated user and call. On every renewal, check that the user still has room access and that the requested room, participant and session belong to that record.

This server helper uses relay.ts from the quickstart. Its input is the trusted record selected after those checks, not an arbitrary browser-supplied token. Save the replacement before returning it so the next renewal uses the latest credential.

TypeScript
import { relay } from './relay.js'
 
type StoredCall = { roomId: string; sessionId: string; participantToken: string }
 
export async function renewCall(
  call: StoredCall,
  saveToken: (token: string) => Promise<void>,
) {
  const issued = await relay.tokens.renew(call.roomId, {
    participantToken: call.participantToken,
    sessionId: call.sessionId,
    ttlSeconds: 3600,
  })
  await saveToken(issued.token)
  return { token: issued.token }
}

Expose the result through your authenticated /api/renew-participant endpoint. Use the intended lifetime consistently: the default renewal lifetime is not necessarily the lifetime you chose for initial issuance.

The frontend sends identifiers for validation, not permission choices:

React
'use client'
 
import { RelayProvider, RelayRoom, RoomError } from '@relayrtc/react'
import type { CredentialRefreshContext } from '@relayrtc/react'
import type { ReactNode } from 'react'
 
async function refreshToken({ roomId, participantId, sessionId, signal }: CredentialRefreshContext) {
  const response = await fetch('/api/renew-participant', {
    method: 'POST', signal, headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ roomId, participantId, sessionId }),
  })
  if ([401, 403, 404].includes(response.status)) return null
  if (!response.ok) {
    throw new RoomError('TOKEN_REFRESH_FAILED', 'Participant renewal is unavailable',
      response.status >= 500 || response.status === 408 || response.status === 429)
  }
  const result: { token: string } = await response.json()
  return result.token
}
 
export function RenewingCall({ token, signalingUrl, children }: {
  token: string; signalingUrl: string; children: ReactNode
}) {
  return <RelayProvider signalingUrl={signalingUrl} refreshToken={refreshToken} autoSubscribe>
    <RelayRoom token={token}>{children}</RelayRoom>
  </RelayProvider>
}

The SDK applies renewed credentials before expiry and uses the replacement for later reconnects. Each token remains limited to 60–3600 seconds; repeated authorized renewals support longer meetings.

Returning null denies renewal. Permanent authorization or identity/permission failures terminate the session. Retryable RoomError failures and ordinary callback exceptions receive bounded retries while the existing token remains valid; expiry still ends the session. Mark permanent application failures non-retryable.

TURN renewal

TURN credentials expire independently of participant tokens. Supply refreshTurnCredentials when creating the client/provider. Your backend must authorize the room/session before issuing temporary relay credentials. The SDK can obtain initial credentials and refresh them before expiry, updating the ICE servers and restarting ICE as needed.

See TURN configuration for the complete callback and backend boundary. autoSubscribe configures neither token nor TURN renewal.

Startup delays

Capture, publication, subscription, ICE negotiation and the first frame are separate stages. A loading indicator communicates progress; it does not shorten transport setup. When startup is consistently slow, inspect those stages and the selected media route rather than repeatedly recreating the room.