> ## AI Agent Context
> Get the complete documentation index at: https://aistudio.google.com/llms.txt
> Use this file to discover all available pages.
> For the full documentation in a single file, fetch: https://aistudio.google.com/llms-full.txt

# Ephemeral tokens in Live API

{% callout type="note" %}
  This feature is in [preview](/docs/models#preview).

{% /callout %}

Ephemeral tokens are short-lived authentication tokens for accessing the Gemini
API through [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API). They are designed to enhance security when
you are connecting directly from a user's device to the API (a
[client-to-server](/docs/live-api#implementation-approach)
implementation). Like standard API keys, ephemeral tokens can be extracted from
client-side applications such as web browsers or mobile apps. But because
ephemeral tokens expire quickly and can be restricted, they significantly reduce
the security risks in a production environment. You should use them when
accessing the Live API directly from client-side applications to enhance API
key security.

{% callout type="note" %}
  At this time, ephemeral tokens are only compatible with [Live API](/docs/live-api).

{% /callout %}

## How ephemeral tokens work  {% id="how-it-works" %}

Here's how ephemeral tokens work at a high level:

1.  Your client (e.g. web app) authenticates with your backend.
2.  Your backend requests an ephemeral token from Gemini API's provisioning
  service.
3.  Gemini API issues a short-lived token.
4.  Your backend sends the token to the client for WebSocket connections to Live
  API. You can do this by swapping your API key with an ephemeral token.
5.  The client then uses the token as if it were an API key.

![](https://www.gstatic.com/cloud-cms/e24bc6220f8251c4ac104a19e823e452.png)

This enhances security because even if extracted, the token is short-lived,
unlike a long-lived API key deployed client-side. Since the client sends data
directly to Gemini, this also improves latency and avoids your backends needing
to proxy the real time data.

## Create an ephemeral token  {% id="create-a-token" %}

Here is a simplified example of how to get an ephemeral token from Gemini.
By default, you'll have 1 minute to start new Live API sessions using the token
from this request (`newSessionExpireTime`), and 30 minutes to send messages over
that connection (`expireTime`).

{% tabs %}
  {% tab label="Python" %}
  ```python
  import datetime
  from google import genai
  
  now = datetime.datetime.now(tz=datetime.timezone.utc)
  
  client = genai.Client()
  
  token = client.auth_tokens.create(
      config = {
      'uses': 1, # The ephemeral token can only be used to start a single session
      'expire_time': now + datetime.timedelta(minutes=30), # Default is 30 minutes in the future
      # 'expire_time': '2025-05-17T00:00:00Z',   # Accepts isoformat.
      'new_session_expire_time': now + datetime.timedelta(minutes=1), # Default 1 minute in the future
    }
  )
  
  # You'll need to pass the value under token.name back to your client to use it
  ```

  {% /tab %}

  {% tab label="JavaScript" %}
  ```javascript
  import { GoogleGenAI } from "@google/genai";
  
  const client = new GoogleGenAI({});
  const expireTime = new Date(Date.now() + 30 * 60 * 1000).toISOString();
  
  const token = await client.authTokens.create({
      config: {
        uses: 1, // The default
        expireTime: expireTime, // Default is 30 mins
        newSessionExpireTime: new Date(Date.now() + (1 * 60 * 1000)), // Default 1 minute in the future
      },
    });
  ```

  {% /tab %}

  {% tab label="REST" %}
  ```bash
  curl -X POST "https://generativelanguage.googleapis.com/v1beta/auth_tokens" \
    -H "x-goog-api-key: ${GEMINI_API_KEY}" \
    -H "Content-Type: application/json" \
    -d '{
      "uses": 1,
      "expireTime": "YYYY-MM-DDTHH:MM:SSZ",
      "newSessionExpireTime": "YYYY-MM-DDTHH:MM:SSZ"
    }'
  ```

  {% /tab %}

{% /tabs %}

For `expireTime` value constraints, defaults, and other field specs, see the
[API reference](https://ai.google.dev/api/live#ephemeral-auth-tokens).
Within the `expireTime` timeframe, you'll need
[`sessionResumption`](/docs/live-api/session-management#session-resumption) to
reconnect the call every 10 minutes (this can be done with the same token even
if `uses: 1`).

It's also possible to lock an ephemeral token to a set of configurations. This
might be useful to further improve security of your application and keep your
system instructions on the server side.

{% tabs %}
  {% tab label="Python" %}
  ```python
  from google import genai
  
  client = genai.Client()
  
  token = client.auth_tokens.create(
      config = {
      'uses': 1,
      'live_connect_constraints': {
          'model': 'gemini-3.8-live',
          'config': {
              'session_resumption':{},
              'response_modalities':['AUDIO']
          }
      },
      }
  )
  
  # You'll need to pass the value under token.name back to your client to use it
  ```

  {% /tab %}

  {% tab label="JavaScript" %}
  ```javascript
  import { GoogleGenAI } from "@google/genai";
  
  const client = new GoogleGenAI({});
  const expireTime = new Date(Date.now() + 30 * 60 * 1000).toISOString();
  
  const token = await client.authTokens.create({
      config: {
          uses: 1, // The default
          expireTime: expireTime,
          liveConnectConstraints: {
              model: 'gemini-3.8-live',
              config: {
                  sessionResumption: {},
                  responseModalities: ['AUDIO']
              }
          },
      }
  });
  
  // You'll need to pass the value under token.name back to your client to use it
  ```

  {% /tab %}

  {% tab label="REST" %}
  ```bash
  curl -X POST "https://generativelanguage.googleapis.com/v1beta/auth_tokens" \
    -H "x-goog-api-key: ${GEMINI_API_KEY}" \
    -H "Content-Type: application/json" \
    -d '{
      "uses": 1,
      "expireTime": "YYYY-MM-DDTHH:MM:SSZ",
      "liveConnectConstraints": {
        "model": "models/gemini-3.8-live",
        "config": {
          "sessionResumption": {},
          "responseModalities": ["AUDIO"]
        }
      }
    }'
  ```

  {% /tab %}

{% /tabs %}

You can also lock a subset of fields, see the
[SDK documentation](https://googleapis.github.io/python-genai/genai.html#genai.types.CreateAuthTokenConfig.lock_additional_fields)
for more info.

## Connect to Live API with an ephemeral token  {% id="connect-live-api" %}

Once you have an ephemeral token, you use it as if it were an API key (but
remember, it only works for the live API, and only with the `v1beta` version of
the API).

The use of ephemeral tokens only adds value when deploying applications that
follow the
[client-to-server implementation](/docs/live-api#implementation-approach)
approach.

{% tabs %}
  {% tab label="JavaScript" %}
  ```javascript
  import { GoogleGenAI, Modality } from '@google/genai';
  
  // Use the token generated in the "Create an ephemeral token" section here
  const ai = new GoogleGenAI({
    apiKey: token.name
  });
  const model = 'gemini-3.8-live';
  const config = { responseModalities: [Modality.AUDIO] };
  
  async function main() {
  
    const session = await ai.live.connect({
      model: model,
      config: config,
      callbacks: { ... },
    });
  
    // Send content...
  
    session.close();
  }
  
  await main();
  ```

  {% /tab %}

{% /tabs %}

{% callout type="note" %}
  If not using the SDK, note that ephemeral tokens must either be passed in
  an `access_token` query parameter, or in an HTTP `Authorization` prefixed by the
  [auth-scheme](https://datatracker.ietf.org/doc/html/rfc7235#section-2.1)
  `Token`.

{% /callout %}

See [Get started with Live API](/docs/live-api) for more examples.

## Best practices  {% id="best-practices" %}

*   Set a short expiration duration using the `expire_time` parameter.
*   Tokens expire, requiring re-initiation of the provisioning process.
*   Verify secure authentication for your own backend. Ephemeral tokens will
  only be as secure as your backend authentication method.
*   Generally, avoid using ephemeral tokens for backend-to-Gemini connections,
  as this path is typically considered secure.

## Limitations  {% id="limitations" %}

Ephemeral tokens are only compatible with [Live API](/docs/live-api) at this time.

## What's next  {% id="whats-next" %}

*   Read the Live API [reference](https://ai.google.dev/api/live#ephemeral-auth-tokens)
  on ephemeral tokens for more information.

