Skip to main content

Overview

The createRealtimeClientSecret function creates a temporary client secret from OpenAI’s Realtime API that can be safely used in frontend applications. This allows frontend clients to connect directly to OpenAI’s Realtime API without exposing your API key.

Function Signature

async function createRealtimeClientSecret(
  opts: NavaiVoiceBackendOptions,
  req?: CreateClientSecretRequest
): Promise<OpenAIRealtimeClientSecretResponse>

Parameters

opts
NavaiVoiceBackendOptions
required
Backend configuration options.
req
CreateClientSecretRequest
Request-specific overrides for the client secret.

Return Type

OpenAIRealtimeClientSecretResponse
object
The response from OpenAI containing the client secret.

Example Usage

import { createRealtimeClientSecret } from '@navai/voice-backend';

const opts = {
  openaiApiKey: process.env.OPENAI_API_KEY,
  defaultModel: 'gpt-realtime',
  defaultVoice: 'marin',
  clientSecretTtlSeconds: 600
};

const secret = await createRealtimeClientSecret(opts);

console.log('Client secret:', secret.value);
console.log('Expires at:', new Date(secret.expires_at * 1000));

Environment Variables

When using getNavaiVoiceBackendOptionsFromEnv(), the following environment variables are read:
  • OPENAI_API_KEY - Your OpenAI API key
  • OPENAI_REALTIME_MODEL - Default model
  • OPENAI_REALTIME_VOICE - Default voice
  • OPENAI_REALTIME_INSTRUCTIONS - Default instructions
  • OPENAI_REALTIME_LANGUAGE - Default language
  • OPENAI_REALTIME_VOICE_ACCENT - Default voice accent
  • OPENAI_REALTIME_VOICE_TONE - Default voice tone
  • OPENAI_REALTIME_CLIENT_SECRET_TTL - TTL in seconds (default: 600)
  • NAVAI_ALLOW_FRONTEND_API_KEY - Set to “true” to allow frontend API keys

Error Handling

The function throws errors in the following cases:
  • Missing API key (no openaiApiKey and allowApiKeyFromRequest is false)
  • Invalid clientSecretTtlSeconds (must be between 10 and 7200)
  • OpenAI API request failure (non-200 response)
  • Request API key provided but allowApiKeyFromRequest is false
Always validate the expires_at timestamp on the client side and request a new secret before expiration.

Source Reference

Defined in: packages/voice-backend/src/index.ts:160

Build docs developers (and LLMs) love