Appearance
Authentication Overview
The SDK handles JWT access tokens, refresh tokens, and session persistence automatically. Frontend developers never need to manually attach Authorization headers.
Listening to Auth State
The SDK uses an event emitter pattern. You can subscribe to onAuthStateChanged to reactively update your UI when a user logs in or out. This is highly useful for React useEffect or Vue onMounted.
javascript
// Subscribe to auth changes
const unsubscribe = sdk.auth.onAuthStateChanged((user) => {
if (user) {
console.log(`Welcome back, ${user.username}! 2FA: ${user.isTwoFactorEnabled}`);
} else {
console.log('User is logged out.');
// Show login screen
}
});
// Call this when your component unmounts to prevent memory leaks
// unsubscribe();Session Restore (sessionReady)
If a user refreshes the page, the browser loses memory of the access token.
The SDK automatically detects a stored refresh token on initialization and silently calls the backend /v1/auth/refresh endpoint. Once finished, it fires onAuthStateChanged with the restored user. No UI flickering or forced logouts required.
Because restore is asynchronous, the SDK exposes a readiness signal; await it before rendering protected routes:
javascript
const authenticated = await sdk.auth.sessionReady;
// true = a session was restored; safe to render the app nowYou can also read when the current access token expires (useful for "session expires in X min" UI):
javascript
sdk.auth.tokenExpiry; // epoch ms, or null when logged outThe SDK also proactively refreshes the access token before it expires (default window: 60 seconds, configurable via refreshWindowMs in the SDK config), so users with open tabs are never interrupted.
Getting the Current User
You can synchronously access the current user object anywhere in your app:
javascript
const user = sdk.auth.getCurrentUser();
if (sdk.auth.isAuthenticated()) {
console.log(`User ID: ${user.id}`);
}To force a fresh fetch of the user's profile from the backend:
javascript
const freshUser = await sdk.auth.getProfile();Logout
javascript
await sdk.auth.logout();This attempts to invalidate the session on the backend and immediately clears all local SDK state, firing onAuthStateChanged with null; even if the backend call fails, the user is never stuck logged in. See Session Lifecycle.