Complete guide to authentication and token management in the TypeScript SDK
The CommerceEngine SDK provides two sophisticated approaches to token management, designed to handle everything from simple prototyping to production-scale applications with automatic token refresh and persistence.
// Set tokens for all clientsawait sdk.setTokens(accessToken, refreshToken);// Clear all tokensawait sdk.clearTokens();// Check authentication statusconst isLoggedIn = await sdk.isLoggedIn();const isAnonymous = await sdk.isAnonymous();// Get user information from the APIconst { data: userData } = await sdk.auth.retrieveUser();const user = userData?.content; // The user object is in the `content` propertyconst userId = user?.id;
const sdk = new StorefrontSDK({ storeId: "your-store-id", apiKey: "your-api-key", tokenStorage: new BrowserTokenStorage(), onTokensUpdated: (accessToken, refreshToken) => { // Called when: // - User logs in // - Tokens are refreshed automatically // - setTokens() is called manually console.log("Tokens updated"); // Update your application state updateUserState({ authenticated: true }); // Send to analytics analytics.identify(getUserIdFromToken(accessToken)); }, onTokensCleared: () => { // Called when: // - User logs out // - Tokens are invalid and can't be refreshed // - clearTokens() is called manually console.log("Tokens cleared"); // Update your application state updateUserState({ authenticated: false }); // Redirect to login router.push("/login"); }});
Token Management Summary: The SDKβs automatic token management handles all the complexity of authentication, token refresh, and storage, allowing you to focus on building your application features while ensuring a seamless user experience.