Token Types
There are two types of tokens you can use with the Realtime API:- Public Access Tokens - Used to read and subscribe to run data. Can be used in both the frontend and backend.
- Trigger Tokens - Used to trigger tasks from your frontend. These are more secure, single-use tokens that can only be used in the frontend.
Public Access Tokens (for subscribing to runs)
Use Public Access Tokens to subscribe to runs and receive real-time updates in your frontend or backend.Creating Public Access Tokens
You can create a Public Access Token using theauth.createPublicToken function in your backend code:
Scopes
By default a Public Access Token has no permissions. You must specify the scopes you need when creating a Public Access Token:Expiration
By default, Public Access Token’s expire after 15 minutes. You can specify a different expiration time when creating a Public Access Token:- If
expirationTimeis a string, it will be treated as a time span - If
expirationTimeis a number, it will be treated as a Unix timestamp in seconds - If
expirationTimeis aDate, it will be treated as a date
Refreshing an expired token
A realtime stream subscription can outlive its token. Pass arefreshAccessToken callback and a subscription rejected with a 401/403 re-mints once and reconnects, instead of failing. With no refresher, auth errors stay terminal. Mint the fresh token from your backend, where your secret key lives:
refreshAccessToken is available on every realtime hook, and on useApiClient and TriggerAuthContext so hooks under a provider share one refresher.
Auto-generated tokens
When you trigger tasks from your backend, thehandle received includes a publicAccessToken field. This token can be used to authenticate real-time requests in your frontend application.
By default, auto-generated tokens expire after 15 minutes and have a read scope for the specific run(s) that were triggered. You can customize the expiration by passing a publicTokenOptions object to the trigger function.
See our triggering documentation for detailed examples of how to trigger tasks and get auto-generated tokens.
Where should I create tokens? The standard pattern is to create tokens in your backend code (API route, server action) after triggering a task, then pass the token to your frontend. The
handle.publicAccessToken returned by tasks.trigger() already does this for you. You rarely need to create tokens inside a task itself.
