SPB Git

Repository Public

ephemeral-tokens.md 4.0 KB 140 lines markdown

1<!-- source: https://docs.x.ai/developers/model-capabilities/audio/ephemeral-tokens (from https://docs.x.ai/llms-full.txt, retrieved 2026-09-19T05:28:55Z) -->2#### Model Capabilities34# Ephemeral Tokens56Ephemeral tokens provide secure, short-lived authentication for client-side applications. Use them when connecting to the [Speech to Speech API](/developers/model-capabilities/audio/speech-to-speech) from browsers or mobile apps to avoid exposing your API key.78## How It Works9101. Your **server** requests an ephemeral token from xAI using your API key112. Your server passes the ephemeral token to the **client**123. The **client** uses the ephemeral token to authenticate the WebSocket connection134. The token expires automatically after the configured duration1415> [!WARNING]16>17> **Never expose your API key in client-side code.** Always use ephemeral tokens for browser and mobile applications.1819## Creating Ephemeral Tokens2021You need to set up a server endpoint to fetch the ephemeral token from xAI. The ephemeral token gives the holder scoped access to resources.2223**Endpoint:** `POST https://api.x.ai/v1/realtime/client_secrets`2425```bash26curl --url https://api.x.ai/v1/realtime/client_secrets \27  -H "Content-Type: application/json" \28  -H "Authorization: Bearer $XAI_API_KEY" \29  --data '{30    "expires_after": {31      "seconds": 30032    }33  }'3435# Note: Does not support "session" or "expires_after.anchor" fields36```3738```pythonWithoutSDK39# Example ephemeral token endpoint with FastAPI4041import os42import httpx43from fastapi import FastAPI4445app = FastAPI()46SESSION_REQUEST_URL = "https://api.x.ai/v1/realtime/client_secrets"47XAI_API_KEY = os.getenv("XAI_API_KEY")4849@app.post("/session")50async def get_ephemeral_token():51    # Send request to xAI endpoint to retrieve the ephemeral token52    async with httpx.AsyncClient() as client:53        response = await client.post(54            url=SESSION_REQUEST_URL,55            headers={56                "Authorization": f"Bearer {XAI_API_KEY}",57                "Content-Type": "application/json",58            },59            json={"expires_after": {"seconds": 300}},60        )6162    # Return the response body from xAI with ephemeral token63    return response.json()64```6566```javascriptWithoutSDK67// Example ephemeral token endpoint with Express6869import express from 'express';7071const app = express();72const SESSION_REQUEST_URL = "https://api.x.ai/v1/realtime/client_secrets";7374app.use(express.json());7576app.post("/session", async (req, res) => {77  const r = await fetch(SESSION_REQUEST_URL, {78    method: "POST",79    headers: {80      Authorization: \`Bearer \${process.env.XAI_API_KEY}\`,81      "Content-Type": "application/json",82    },83    body: JSON.stringify({84      expires_after: { seconds: 300 }85    }),86  });8788  const data = await r.json();89  res.json(data);90});9192app.listen(8081);93```9495## Using Ephemeral Tokens9697The ephemeral token can be used in the same fashion as an API key:9899```pythonWithoutSDK100import os101import websockets102103base_url = "wss://api.x.ai/v1/realtime?model=grok-voice-latest"104105# Connect with API key in Authorization header106async with websockets.connect(107    uri=base_url,108    ssl=True,109    additional_headers={"Authorization": f"Bearer {OBTAINED_EPHEMERAL_TOKEN}"}110) as websocket:111    # WebSocket connection is now authenticated112    pass113```114115```javascriptWithoutSDK116import WebSocket from "ws";117118const baseUrl = "wss://api.x.ai/v1/realtime?model=grok-voice-latest";119120// Connect with API key in Authorization header121const ws = new WebSocket(baseUrl, {122  headers: {123    Authorization: "Bearer " + OBTAINED_EPHEMERAL_TOKEN,124    "Content-Type": "application/json",125  },126});127128ws.on("open", () => {129  console.log("Connected with ephemeral token authentication");130});131```132133### Browser WebSocket Authentication134135If 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:136137```javascriptWithoutSDK138new WebSocket("wss://api.x.ai/v1/realtime", [\`xai-client-secret.\${OBTAINED_EPHEMERAL_TOKEN}\`]);139```140
Files main
Menu

Theme