Model Capabilities

Ephemeral Tokens

View as Markdown

Ephemeral tokens provide secure, short-lived authentication for client-side applications. Use them when connecting to the Voice Agent API from browsers or mobile apps to avoid exposing your API key.


How It Works

  1. Your server requests an ephemeral token from xAI using your API key
  2. Your server passes the ephemeral token to the client
  3. The client uses the ephemeral token to authenticate the WebSocket connection
  4. The token expires automatically after the configured duration

Never expose your API key in client-side code. Always use ephemeral tokens for browser and mobile applications.


Creating Ephemeral Tokens

You need to set up a server endpoint to fetch the ephemeral token from xAI. The ephemeral token gives the holder scoped access to resources.

Endpoint: POST https://api.x.ai/v1/realtime/client_secrets

# Example ephemeral token endpoint with FastAPI

import os
import httpx
from fastapi import FastAPI

app = FastAPI()
SESSION_REQUEST_URL = "https://api.x.ai/v1/realtime/client_secrets"
XAI_API_KEY = os.getenv("XAI_API_KEY")

@app.post("/session")
async def get_ephemeral_token():
    # Send request to xAI endpoint to retrieve the ephemeral token
    async with httpx.AsyncClient() as client:
        response = await client.post(
            url=SESSION_REQUEST_URL,
            headers={
                "Authorization": f"Bearer {XAI_API_KEY}",
                "Content-Type": "application/json",
            },
            json={"expires_after": {"seconds": 300}},
        )

    # Return the response body from xAI with ephemeral token
    return response.json()

Using Ephemeral Tokens

The ephemeral token can be used in the same fashion as an API key:

import os
import websockets

base_url = "wss://api.x.ai/v1/realtime"

# Connect with API key in Authorization header
async with websockets.connect(
    uri=base_url,
    ssl=True,
    additional_headers={"Authorization": f"Bearer {OBTAINED_EPHEMERAL_TOKEN}"}
) as websocket:
    # WebSocket connection is now authenticated
    pass

Browser WebSocket Authentication

If you need to send the ephemeral token from the browser, you can add the ephemeral token with a prefix xai-client-secret. to the sec-websocket-protocol header:

Javascript

new WebSocket("api.x.ai", [`xai-client-secret.${OBTAINED_EPHEMERAL_TOKEN}`]);

Did you find this page helpful?