> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fish.audio/llms.txt
> Use this file to discover all available pages before exploring further.

# One-Time Ephemeral Tokens

> Mint short-lived single-use ek-fish- tokens on your backend so browsers, mobile, and desktop apps connect directly to Fish Audio

Never embed a long-lived `sk-fish-` API key in browser JavaScript, mobile apps, or desktop binaries. Instead, mint a short-lived, **one-time (single-use) `ek-fish-` ephemeral token** on your backend and hand it to your client so the client can connect directly to Fish Audio with low latency and zero audio proxying.

## Prerequisites

* A **Scoped** API key created on [API Keys](https://fish.audio/app/api-keys/) with:
  * `tokens:mint`, and
  * At least one ephemeral-capable inference scope you want to delegate (`tts:write`, `stt:write`, `voice_design:write`, or `realtime:write`; `agents:session` is also accepted by the mint endpoint for gateway-routed sessions, while REST `POST /v1/agent/sessions` uses a `sk-fish-` key).
* Sufficient API credit on your account (or an active contract / package).

> [!WARNING]
>
> **Classic** API keys cannot mint ephemeral tokens (`403
>     classic_key_cannot_mint`). Passing any non-`ek-fish-` credential in `?token=`,
> or passing a long-lived `sk-fish-` key in `Sec-WebSocket-Protocol`, is
> rejected with `400` (`x-fish-error-code: long_lived_key_in_query_forbidden`).

## How it works

```text theme={null}
1. Client (browser / mobile / desktop)  ──►  Your backend (authenticated user session)
2. Your backend  ──POST /v1/auth/tokens──►   Fish Audio API (using Scoped sk-fish- key)
                 ◄── 201 { token: "ek-fish-...", expires_in } ──
3. Your backend  ──►  Client (returns ek-fish- token)
4. Client  ──direct WS or HTTP──►  api.fish.audio edge gateway
                                   • Atomically redeems single-use token
                                   • Enforces allowed_origins, scopes & parent spend limit
                                   • Bills usage to the parent Scoped API key
```

## Step 1: Mint a token on your backend

Call [`POST /v1/auth/tokens`](https://docs.fish.audio/api-reference/endpoint/apikey/mint-ephemeral-token) from your trusted server right before the client starts a session. Restrict `scopes`, `ttl_seconds`, `max_session_duration_seconds`, and (for browser clients) `allowed_origins` as tightly as your use case allows.

```bash cURL theme={null}
curl -X POST https://api.fish.audio/v1/auth/tokens \
  -H "Authorization: Bearer $FISH_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "scopes": ["stt:write"],
    "ttl_seconds": 120,
    "max_session_duration_seconds": 1800,
    "allowed_origins": ["https://app.example.com"],
    "end_user_id": "user_42"
  }'
```

```python Python theme={null}
import os
import requests

resp = requests.post(
    "https://api.fish.audio/v1/auth/tokens",
    headers={
        "Authorization": f"Bearer {os.environ['FISH_API_KEY']}",
        "Content-Type": "application/json",
    },
    json={
        "scopes": ["stt:write"],
        "ttl_seconds": 120,
        "max_session_duration_seconds": 1800,
        "allowed_origins": ["https://app.example.com"],
        "end_user_id": "user_42",
    },
    timeout=10,
)
resp.raise_for_status()
token_payload = resp.json()
# Return token_payload["token"] ("ek-fish-...") to your authenticated client
```

```javascript Node.js theme={null}
const resp = await fetch("https://api.fish.audio/v1/auth/tokens", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.FISH_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    scopes: ["stt:write"],
    ttl_seconds: 120,
    max_session_duration_seconds: 1800,
    allowed_origins: ["https://app.example.com"],
    end_user_id: "user_42",
  }),
});

if (!resp.ok) {
  throw new Error(`Token mint failed: ${resp.status}`);
}

const { token, expires_at } = await resp.json();
// Return `token` ("ek-fish-...") to your authenticated client
```

## Step 2: Connect directly from the client

### Browser WebSocket (Realtime STT and Live TTS)

Browser `WebSocket` APIs cannot set custom request headers. Pass `["bearer", token]` as the WebSocket subprotocol list instead:

```javascript Browser theme={null}
// Fetch a fresh single-use ek-fish- token from your own backend endpoint
const { token } = await fetch("/api/fish-token", { method: "POST" }).then(r =>
  r.json()
);

const ws = new WebSocket("wss://api.fish.audio/v1/asr/realtime", [
  "bearer",
  token,
]);
ws.binaryType = "arraybuffer";

ws.onopen = () => {
  // Send your initial MessagePack config frame (see WebSocket Realtime Speech to Text)
};

ws.onclose = event => {
  if (event.code === 4008) {
    // Ephemeral token max_session_duration_seconds elapsed; mint a fresh token to reconnect
  } else if (event.code === 4002) {
    // Parent API key USD spend limit reached
  }
};
```

During the WebSocket handshake, the edge gateway extracts the `ek-fish-` token from `Sec-WebSocket-Protocol`, strips it before forwarding upstream, and echoes only `Sec-WebSocket-Protocol: bearer` in the `101 Switching Protocols` response per RFC 6455.

> [!NOTE]
>
> **Model selection on browser WebSockets:** Because browser `WebSocket`
> connections cannot send custom headers like `model`, direct browser
> connections use each WebSocket endpoint's default model (`transcribe-stream-1`
> on `/v1/asr/realtime`, `s2.1-pro` on `/v1/tts/live`). Native mobile/desktop
> clients and server relays can send the `model` header on WebSocket upgrades,
> and browser HTTP `fetch` requests can send `model` directly via CORS.

### Browser HTTP `fetch` (TTS, STT, Voice Design)

Inference endpoints served through the edge gateway handle browser CORS preflights (`OPTIONS`), set `Vary: Origin`, and expose Fish Audio diagnostic headers (`x-fish-trace-id`, `x-fish-error-code`, `x-fish-error-source`, `x-fish-free-model`, `x-fish-required-scope`, `ratelimit-limit-concurrency`, `ratelimit-current-concurrency`, `retry-after`).

Send the ephemeral token in the standard `Authorization: Bearer` header (you can also set the `model` header normally):

```javascript Browser theme={null}
// Fetch a fresh single-use ek-fish- token minted with scopes: ["tts:write"]
const { token } = await fetch("/api/fish-tts-token", { method: "POST" }).then(
  r => r.json()
);

const res = await fetch("https://api.fish.audio/v1/tts", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${token}`,
    "Content-Type": "application/json",
    model: "s3-pro",
  },
  body: JSON.stringify({
    text: "Hello directly from the browser!",
    format: "mp3",
  }),
});

if (!res.ok) {
  const errorCode = res.headers.get("x-fish-error-code");
  throw new Error(`TTS failed (${res.status}): ${errorCode}`);
}

const audioBlob = await res.blob();
```

> [!NOTE]
>
> Each `ek-fish-` token is **single-use**: mint a fresh token per request or per
> WebSocket connection. If a client cannot set headers or subprotocols, you can
> also pass `?token=ek-fish-...` in the query string — the edge gateway scrubs
> `token` from the URI before logging or forwarding upstream.

## Security controls and runtime behavior

* **Atomic single-use redemption (mint a fresh token on retries):** A token is consumed atomically on its first redemption, before concurrency checks and upstream forwarding. If that request fails later with `429` or `5xx`, the token is already spent — mint a fresh `ek-fish-` token before retrying, because replaying the old token returns `401` (`x-fish-error-code: ephemeral_token_already_used`).
* **No token chaining:** An `ek-fish-` token cannot call `POST /v1/auth/tokens` (`403 ephemeral_token_cannot_mint`) or management endpoints such as `GET /apikey/self`.
* **Origin pinning (browser `http`/`https` only):** When `allowed_origins` is provided (up to 20 exact `http://host[:port]` or `https://host[:port]` origins; no wildcards, paths, or custom schemes such as `capacitor://`, `tauri://`, `app://`, or `file://`), the edge gateway requires the request's `Origin` header to match an entry in the list. Native mobile or desktop clients that send no `Origin` header receive `403` (`origin_not_allowed`) when `allowed_origins` is set — omit `allowed_origins` for non-browser clients.
* **Live parent key re-check:** At redemption time, Fish Audio re-verifies the parent scoped API key. Revoking the parent key, removing a required scope, or hitting its USD spend limit immediately blocks all unredeemed `ek-fish-` tokens minted by that key.
* **WebSocket session guardrails:**
  * Close code **`4008`** (`session_duration_exceeded`): the connection reached `max_session_duration_seconds`. Note that `max_session_duration_seconds` cannot extend an endpoint's own maximum session cap (for example, 3,600 seconds / close `4413` on `/v1/asr/realtime`) — whichever limit is lower fires first.
  * Close code **`4002`** (`api_key_spend_limit_exceeded`): the parent API key reached its USD spend limit mid-session.
* **Gateway error codes during redemption:**

| HTTP Status | `x-fish-error-code` header | Meaning |
| - | - | - |
| `400` | `long_lived_key_in_query_forbidden` | A non-`ek-fish-` value was sent in `?token=`, or a long-lived `sk-fish-` key was sent in `Sec-WebSocket-Protocol`. |
| `401` | `invalid_ephemeral_token` | Token is unknown, malformed, already reaped after expiry, or its parent API key was revoked or expired. |
| `401` | `ephemeral_token_already_used` | Single-use token was already redeemed on an earlier request or connection. |
| `401` | `ephemeral_token_expired` | Token passed its `expires_at` TTL before being redeemed. |
| `402` | `insufficient_balance` | Account has insufficient API credit for the requested model. |
| `402` | `api_key_spend_limit_exceeded` | The parent API key reached its USD spend limit. |
| `403` | `origin_not_allowed` | Request `Origin` header is missing or does not match `allowed_origins`. |
| `403` | `insufficient_scope` | Token (or parent key) does not have the required scope (`x-fish-required-scope`). |
| `503` | `ephemeral_auth_unavailable` | Ephemeral authentication service is temporarily unavailable; retry with backoff. |

> [!TIP]
>
> Expired or already-used tokens are automatically removed after `expires_at`,
> after which lookups return `invalid_ephemeral_token`. Handle all three `401`
> ephemeral codes (`invalid_ephemeral_token`, `ephemeral_token_already_used`,
> `ephemeral_token_expired`) the same way: request a fresh `ek-fish-` token from
> your backend.

## Related

> [card] [POST /v1/auth/tokens](https://docs.fish.audio/api-reference/endpoint/apikey/mint-ephemeral-token.md)
>
> Full request, response, rate limit, and error reference.

> [card] [API Key Types, Scopes, and Spend Limits](https://docs.fish.audio/developer-guide/getting-started/api-keys-and-scopes.md)
>
> Configure Scoped keys, all 12 scopes, and per-key USD spend caps.

> [card] [WebSocket Realtime Speech to Text](https://docs.fish.audio/api-reference/endpoint/websocket/asr-realtime.md)
>
> Connect from browsers or servers to wss\://api.fish.audio/v1/asr/realtime.

> [card] [WebSocket TTS Streaming](https://docs.fish.audio/api-reference/endpoint/websocket/tts-live.md)
>
> Stream real-time text to speech over WebSocket.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.