Handling the Embed Token
When integrating an embeddable component, ensuring secure and continuous access to your data is critical. The embeddable requires an embed token for authentication, and because these tokens expire after a while, you need to implement a strategy to refresh them automatically. This page provides a technical walkthrough on managing the embed token with our library.
Fetching a New Token
Tokens are typically retrieved from your backend service. Since fetching might involve asynchronous operations (like API calls), you can update the token after the embeddable has been initialized.
import { Embeddable } from 'embeddables';
import { getEmbedToken } from './your-token-retrieval-script';
const embeddable = new Embeddable({})
// Function to asynchronously fetch a new token from the server.
const setTokenAsync = async () => {
const token = await getEmbedToken();
// Update the token in the embeddable's state.
embeddable.updateEmbedToken(token);
};
setTokenAsync();
There are several nice features with the updating of the embed token—you can pass in the following types:
embedToken?: string
| Promise<string>
| ((options: { signal: AbortSignal }) => Promise<string> | string)
Meaning that this is the same as above:
const embeddable = new Embeddable({
embedToken: getEmbedToken // Async function that returns the embedToken
})
Internal handling
When using the EmbeddableView, the token is handled by the Embeddable class it was created from. This means that you only need to update the token on the Embeddable class, which will in turn automatically update all of its EmbeddableViews.
Auto-refreshing token on expiration
By using the ‘tokenExpired‘-event listener, you can create an intuitive way to refresh your token once it expires, ensuring continuous service to your users.
embeddable.on('tokenExpired', () => {
setTokenAsync()
})
Best practices
As getting a token from our services is a heavy and time-consuming operation, we recommend to cache the token.