When a SaaS product adds a real-time AI avatar, it is tempting to treat credentials as a small implementation detail. In Direct Mode, they are a useful architectural boundary.
Spatius uses a Session Token so the client can establish its own connection to Motion Server without receiving your server-side API Key. That does not turn Spatius into your agent layer or your identity system. Your application still owns user authentication, authorization, conversation logic, ASR, LLM, TTS, turn-taking, and handoff policy. Spatius receives avatar speech audio, returns motion data, and AvatarKit renders the avatar locally. Spatius’ developer docs map makes that separation explicit; the How It Works overview shows the same boundary between cloud motion data and local rendering.
This guide explains how to make the token boundary deliberate: what belongs in the client, what belongs in your backend, and what to plan for when a client needs to reconnect.
Key takeaways
- Use a Spatius Session Token only for a Direct Mode client connection; it is not a replacement for your SaaS login or authorization model.
- Keep
SPATIUS_API_KEYonly on your backend. The client should request a Session Token from your own authenticated endpoint. - Issue a fresh token for each connection. Spatius documents Session Tokens as short-lived, designed for single use, with a maximum validity of 24 hours.
- Keep the token endpoint small. It mints tokens; it does not relay avatar audio, receive motion data, or run your ASR, LLM, or TTS pipeline.
- Treat reconnects as a normal product state: a new connection after expiry needs a fresh token, while an already-established connection is not affected solely because the token reaches its expiry time.
Start with the system boundary
Before writing an endpoint, name the responsibilities clearly. In Direct Mode, the client runs AvatarKit. It uses a Session Token to open a Motion Server WebSocket, sends avatar speech audio, receives motion data, and renders the avatar locally. The small backend service exists because the API Key must stay server-side.
For the broader web-application pattern behind that split, see Auth0’s explanation of the Backend for Frontend pattern, Cloudflare’s discussion of scoped API tokens, and Twilio’s guide to basic API security. Those are useful background for the application-owned boundary; they do not redefine the Spatius runtime.
Authenticated product client
│ asks for a Session Token
▼
Your application backend
│ calls Spatius Console API with the API Key
▼
Spatius Console API
│ returns a Session Token
▼
Client sets the token, then starts AvatarKit
│
▼
Motion Server → motion data → local AvatarKit rendering
The token endpoint is deliberately outside the real-time avatar media path. It does not need to proxy the Motion Server connection, inspect speech audio, or receive motion data. That is the core Direct Mode model described in the Direct Mode overview.
Keep the data path just as explicit. Spatius’ Audio guidance covers the audio format, timing, buffering, and interruption considerations at the avatar runtime edge; none of that makes token issuance an audio-processing service.
This distinction is useful beyond security. It keeps the token service easy to reason about: your app decides whether a signed-in user is allowed to start an avatar experience, and the service returns only the temporary credential required to make that client connection.
If that boundary does not describe your architecture, pause before implementing it. The integration-path guide separates Direct Mode from platform and backend-owned paths, so the credential model follows the runtime path you actually choose.
For a low-risk first validation, the Quickstarts overview starts Direct Mode with a Session Token and sample audio before a team layers in its own real-time conversation stack.
Use Session Tokens only when you are using Direct Mode
Session Tokens belong to the Direct Mode path. In that path, the client opens the Motion Server WebSocket itself.
They are not a universal Spatius credential to add to every integration. The Session Token Auth Flow states that Platform Integrations, Backend Mode, and the RTC Adapter path use backend-mode transport instead; the client does not open this Direct Mode WebSocket and does not need a Spatius Session Token.
This is an important design check. If your architecture deliberately routes avatar runtime traffic through a backend-owned pipeline or a platform integration, do not bolt on a client-side Session Token flow just because it sounds more secure. Choose the integration path first, then use the credentials that path requires.
If you are evaluating more than one client surface, use the SDK Capability Matrix to compare the documented SDK support rather than assuming one platform’s integration pattern applies unchanged to another.
For a broader view of public-client token handling, Okta’s article on authentication and authorization for SPAs, Curity’s JWT security checklist, and Okta’s overview of token security practices explain why a browser should receive only the credential needed for its immediate job.
For a product team, the practical question is simple:
Does the client connect directly to Motion Server through Direct Mode? If yes, build a Session Token endpoint. If no, validate the authentication model for the integration path you actually selected.
Treat token issuance as an authorization decision
The Session Token itself authenticates a Direct Mode connection to Motion Server. It should not become the place where your product quietly skips its own permission checks.
Your endpoint should run after the user has already been authenticated by your application. Before it asks Spatius for a token, make an explicit product decision: is this signed-in user allowed to start this avatar experience in this workspace, account, or plan under your own rules?
How your SaaS establishes that signed-in state remains a separate application concern. The OWASP Authentication Cheat Sheet is a useful general reference for that layer; it does not change the role of a Direct Mode Session Token.
That policy is yours to define. Spatius’ documented token request includes an App ID and an expireAt timestamp; it does not replace your tenancy model, your entitlement model, or your audit policy. Keeping that distinction explicit avoids a common mistake: treating a connection credential as if it were a complete user authorization system.
For the broader application-authorization layer, the OWASP Authorization Cheat Sheet is a useful implementation reference. It does not change what a Spatius Session Token does: your application still decides who is permitted to request one. If you are still selecting an integration shape, compare that decision with Build vs. Buy a Real-Time Avatar Layer for Your SaaS Product.
The same boundary should shape your data review. A token endpoint should not become an accidental relay for audio, prompts, or application context; What Data Should a Real-Time AI Avatar Provider Receive? is a useful companion when deciding what belongs on each side of the integration.
A narrow endpoint can follow this sequence:
- Identify the caller using your normal application authentication.
- Load the relevant product context—such as the current workspace, feature entitlement, or selected avatar—using your own data model.
- Decide whether this caller may begin a Direct Mode avatar session.
- If allowed, call the Spatius Console API from the backend with the server-side API Key, App ID, and a chosen expiration time.
- Return the resulting Session Token to that authenticated client only.
Do not accept a user ID, plan name, or permission flag from the browser as proof by itself. Derive the decision from the authenticated server-side context your application already trusts.
That distinction is also consistent with Auth0’s review of the JWT Best Current Practices draft, its explanation of least privilege for access tokens, Cloudflare’s discussion of scoped developer credentials, and Curity’s API security practices. They are general security references, not a substitute for your own entitlement rules.
Keep the token server small and purpose-built
The official flow is intentionally compact. Your business server calls POST /v1/console/session-tokens on the relevant Console API host, supplying appId, expireAt, and the API Key in the X-Api-Key header. The exact request fields are documented in the Session Token API reference, and the corresponding Console and Motion Server endpoints are listed in the Regions reference.
The client flow then has two required ordering rules:
- Receive the token from your backend.
- Call
AvatarSDK.setSessionToken(token)beforeAvatarController.start()opens the Motion Server connection.
For exact Web SDK behavior and method signatures, use the AvatarKit Web SDK Reference rather than treating an integration guide as a complete API contract.
The API Key must never be shipped in browser code, a mobile build, a public configuration object, an example request, or a client-side error report. Spatius classifies it as a server-side secret; App ID and Avatar ID are configuration values that may be used on the client. See the Credentials guide.
The same implementation hygiene appears in Twilio’s article on protecting an Auth Token and Snyk’s discussion of how API secrets leak through development workflows. In this integration, the concrete rule remains simple: the browser never receives SPATIUS_API_KEY.
For your own endpoint, keep the response intentionally boring. Return only what the client needs for the immediate setup. Avoid putting API Keys, unrelated account metadata, application permissions, or internal diagnostics into the response. Avoid writing raw Session Tokens to analytics, client logs, support screenshots, or broad request logs; the OWASP Logging Cheat Sheet is a useful guardrail for the wider logging policy.
The endpoint is still an authenticated application route, so protect its transport as you would any credential-bearing response. The OWASP Transport Layer Security Cheat Sheet is a general reference for that delivery layer; it does not replace your own authentication and authorization checks.
The OWASP Secrets Management Cheat Sheet is a helpful reference when your security team defines the wider lifecycle for server-side secrets. The Spatius-specific rule remains narrow: the API Key stays on your backend; the client receives only the Session Token needed to start its Direct Mode connection.
For operational treatment of sensitive values, Better Stack’s article on safeguarding sensitive data in logs and Datadog’s guide to reducing sensitive-data risk are useful companion reading. They reinforce a product decision this endpoint should already make: retain safe operational metadata, not raw credentials.
Choose expiration around connection setup, not around a user login
The Session Token API requires an expireAt timestamp that is later than now and within 24 hours. The right lifetime is a product and operational decision, but it should be made for the connection-setup window—not copied from a long-lived user login session.
Two lifecycle details shape the experience:
- A new Motion Server connection attempted after the token’s configured expiration will be rejected.
- An already-established connection is not affected simply because the configured expiration time passes.
Spatius also describes Session Tokens as single-use and recommends issuing a fresh one for each connection. That gives your client a straightforward rule: obtain a new token when it is about to create a new Direct Mode connection, including a planned reconnect. The Session Token Auth Flow documents the distinction between a rejected new connection and an already-established connection. Do not assume a previously returned token should be reused for a later connection.
This is also why your token endpoint should be cheap and reliable. It is not called for every audio chunk or every avatar movement; it is part of connecting. If it becomes a complex service with unrelated business logic, recovery becomes harder than it needs to be.
The general token-lifecycle rationale is covered from different angles in Okta’s five token-security tips, its explanation of stolen access-token risk, and Curity’s JWT best-practices checklist. Use those articles for the security principle; use the Spatius Auth Flow for the exact Direct Mode lifecycle.
Design the reconnect path before launch
The happy path is easy to test once. The more useful test is what the product does when a user returns to an avatar view, refreshes the page, or needs a new connection after a token is no longer valid for setup.
Keep the states visible in your own application:
- Requesting token: the client is waiting for your authenticated endpoint.
- Starting avatar connection: the client has a fresh token and is starting AvatarKit.
- Connected: avatar speech audio can be driven through the Direct Mode path.
- Recoverable connection failure: the client can ask for a fresh token and try a new connection according to your product’s retry policy.
- Blocked by product policy: the user is signed in but no longer entitled to launch this experience; explain the next step in product language rather than showing a generic transport error.
Do not promise users that retries will always succeed. Instead, make failure states understandable and keep the retry boundary clean: a new connection gets a newly issued token, and your own product remains in charge of whether to retry, show a fallback, or offer human help.
You can map those product states to AvatarKit’s documented connection-state and error callbacks, rather than making the UI infer a connection outcome from a generic loading state.
Map these states to the SDK’s actual conditions rather than a generic catch-all error. The Client Error Codes guide distinguishes, for example, an expired Session Token from an invalid token, a timeout, and a WebSocket error—each of which may need a different product response.
For the surrounding service design, Infisical’s overview of dynamic and short-lived secrets, Cloudflare’s explanation of service-scoped API tokens, and Twilio’s API-security guide are helpful reminders to keep credentials narrow, renewable, and observable without exposing their values.
Direct Mode token endpoint review checklist
| Review question | A sound implementation looks like | Why it matters |
|---|---|---|
| Is this actually Direct Mode? | The client will directly start AvatarKit’s Motion Server connection. | Session Tokens are for this path, not every Spatius integration. |
| Where does the API Key live? | Only in server-side configuration used by your backend. | The API Key is the credential that calls the Console API. |
| Who can request a token? | A caller already authenticated by your application. | Your app, not the token itself, owns user identity. |
| What permission is checked? | Your backend checks the workspace, feature, and avatar experience rules you define. | A Session Token does not replace tenancy or plan authorization. |
| What is returned to the client? | The fresh Session Token needed for this connection. | Keep the response focused and reduce accidental exposure of unrelated data. |
| When is it issued? | Immediately before a new Direct Mode connection. | Tokens are short-lived and designed for single use. |
| What happens on a new connection after expiry? | The client requests a fresh token, then starts again. | A post-expiry connection is rejected; established connections are treated separately. |
| Does the endpoint relay avatar runtime traffic? | No. It only mints tokens. | Direct Mode puts audio, motion data, and local rendering on the client path. |
| Can you investigate issuance safely? | You retain minimal event metadata needed for operations, without storing raw token values. | Operations need context; credentials should not become log data. |
For deeper reading while reviewing this checklist, compare the secret-lifecycle guidance from Infisical, the API-token scoping approach described by Cloudflare, and the development-workflow risks highlighted by Snyk. The implementation still needs to be evaluated against your own auth and tenancy model.
FAQ
Is a Session Token the same as my product’s login session?
No. A Session Token is the temporary credential a Direct Mode client uses to authenticate its Motion Server connection, as described in the Session Token Auth Flow. Your SaaS should continue to authenticate users and enforce workspace, role, plan, and feature rules with its own systems.
Should the client call the Spatius Console API directly?
No. The documented credential model has your business server call the Console API with the server-side API Key, then return the Session Token to the client. Shipping the API Key to the client would break that boundary.
Do I need a Session Token if I use Backend Mode or a platform integration?
No. The Session Token Auth Flow applies to Direct Mode. As the integration-path guide explains, Backend Mode and platform/RTC paths have their own connection and transport authentication model.
What should happen if a user opens a new avatar connection after the token has expired?
Have the client call your token endpoint again and use the newly issued token before starting the new connection. The Session Token API reference is the source of truth for the configured expiration field; do not treat an old token as a reusable login credential.
Build the boundary once, then keep product control where it belongs
A well-designed Session Token endpoint is not a second agent backend. It is a small, auditable bridge between your authenticated SaaS and a Direct Mode avatar connection. Your application stays in charge of identity, permissions, data, and conversation behavior; Spatius stays focused on turning avatar speech audio into motion data for local rendering.
If your team is establishing a wider token-handling standard, the practical perspectives from Auth0 on the BFF pattern, Okta on SPA token handling, and Curity on API security make useful non-product-specific companions to this integration guide.
If you are deciding whether Direct Mode is the right shape for your product, start with How to Add an AI Avatar to an Existing SaaS AI Agent and How to Pilot an AI Avatar in Your SaaS Product. For an integration conversation tailored to your stack, request a demo.
Sources
- Spatius Developer Docs Map
- Spatius: How It Works
- Spatius Direct Mode Integration
- Spatius Audio
- Spatius Credentials
- Spatius: Choose Your Integration Path
- Spatius Quickstarts
- Spatius SDK Capability Matrix
- Spatius AvatarKit Web SDK Reference
- Spatius Session Token Auth Flow
- Spatius Session Token API
- Spatius Regions
- Spatius Client State & Events
- Spatius Client Error Codes
- OWASP Authentication Cheat Sheet
- OWASP Authorization Cheat Sheet
- OWASP Secrets Management Cheat Sheet
- OWASP Logging Cheat Sheet
- OWASP Transport Layer Security Cheat Sheet
Selected third-party reading
- Auth0: The Backend for Frontend Pattern
- Auth0: JWT Best Current Practices
- Auth0: Access Tokens and Least Privilege
- Okta: Authentication and Authorization for SPAs
- Cloudflare: API Tokens
- Curity: JWT Security Best Practices
- Twilio: Basic API Security Best Practices
- Better Stack: Safeguarding Sensitive Data in Logs
- Datadog: Sensitive Data Management Best Practices
- Infisical: Secrets Management Best Practices