Events
Sesamy JS emits various events throughout the user lifecycle that you can listen to for custom behavior, analytics tracking, and UI updates.
Event Reference
All events are dispatched as standard browser CustomEvent objects that can be listened to using addEventListener.
sesamyJsReady
Fired when the Sesamy JS library has been fully initialized and is ready to use.
Event Detail: {} (empty object)
When it fires:
- After all configurations are loaded
- After authentication state is initialized
- When all API methods are available
Example:
window.addEventListener('sesamyJsReady', () => {
console.log('Sesamy JS is ready!');
// Safe to call API methods now
window.sesamy.auth.isAuthenticated().then((isAuth) => {
console.log('User authenticated:', isAuth);
});
});Common use cases:
- Initialize your app's authentication UI
- Load user profile data
- Check entitlements for protected content
- Set up analytics tracking
sesamyJsAuthInitialized
Fired when the authentication system has been initialized, before the full SDK is ready.
Event Detail: {} (empty object)
When it fires:
- After Auth0 client is configured
- Before redirect callback handling completes
- Before
sesamyJsReadyevent
Example:
window.addEventListener('sesamyJsAuthInitialized', () => {
console.log('Auth system initialized');
// Show loading state while waiting for full initialization
});Common use cases:
- Display early loading indicators
- Handle authentication state transitions
- Debug authentication flow
sesamyJsAuthenticated
Fired when a user successfully authenticates (login, signup, or token refresh).
Event Detail:
{
sub: string; // User ID
email: string; // User email
email_verified: boolean; // Email verification status
name?: string; // User's full name
picture?: string; // Profile picture URL
appState?: any; // Custom metadata passed during login
// ... other JWT claims and user properties
}When it fires:
- After successful redirect-based login
- After successful popup-based login
- After manual token is set via
setToken() - When returning user's session is restored
Example:
window.addEventListener('sesamyJsAuthenticated', (event) => {
const { email, appState, sub } = event.detail;
console.log('User authenticated:', email);
// Access custom login metadata
if (appState?.source === 'registration-wall') {
// Track conversion from paywall
analytics.track('paywall_conversion', {
userId: sub,
source: appState.source,
articleId: appState.articleId,
});
}
// Update UI
document.querySelector('.user-email').textContent = email;
document.querySelector('.premium-content').style.display = 'block';
});Common use cases:
- Update authentication UI
- Track user registration/login events
- Redirect to protected content
- Initialize user-specific features
- Send conversion events to analytics
Canceling auto-reload:
For popup-based logins, you can prevent the automatic page reload by calling preventDefault():
window.addEventListener('sesamyJsAuthenticated', (event) => {
event.preventDefault(); // Prevent automatic reload
console.log('User authenticated, handling manually');
// Manually update UI instead of reloading
});sesamyJsLogout
Fired when a user logs out.
Event Detail: {} (empty object)
When it fires:
- After
window.sesamy.auth.logout()is called - Before redirect to logout URL
Example:
window.addEventListener('sesamyJsLogout', () => {
console.log('User logged out');
// Clear user-specific data
sessionStorage.clear();
// Update UI
document.querySelector('.user-profile').style.display = 'none';
document.querySelector('.login-button').style.display = 'block';
// Track logout event
if (window.gtag) {
window.gtag('event', 'logout');
}
});Common use cases:
- Clear cached user data
- Reset UI to logged-out state
- Track logout analytics
- Clean up user-specific resources
sesamyJsPurchase
Fired when a purchase is completed and the user returns to your site.
Event Detail:
{
itemSrc: string; // The item source identifier for the purchased item
}When it fires:
- After successful purchase completion
- When user returns from checkout with
sesamy-purchasequery parameter
Example:
window.addEventListener('sesamyJsPurchase', (event) => {
const { itemSrc } = event.detail;
console.log('Purchase completed:', itemSrc);
// Show thank you message
showNotification('Thank you for your purchase!');
// Track conversion
if (window.gtag) {
window.gtag('event', 'purchase', {
item_id: itemSrc,
value: /* amount */,
currency: 'USD'
});
}
// Refresh content access
window.location.reload();
});Common use cases:
- Display purchase confirmation
- Track e-commerce conversions
- Unlock purchased content
- Send confirmation emails
- Update user entitlements UI
sesamyUserAttributeChanged
Fired when user attributes (tags) are modified.
Event Detail: {} (empty object)
When it fires:
- After
window.sesamy.setTag()is called - When user tags are updated
Example:
window.addEventListener('sesamyUserAttributeChanged', async () => {
console.log('User attributes changed');
// Refresh user data
const tags = await window.sesamy.getTags();
console.log('Updated tags:', tags);
// Update UI based on new attributes
updateUserBadges(tags);
});Common use cases:
- Refresh user profile UI
- Update personalization features
- Trigger content recommendations
- Sync with external systems
sesamyJsClearCache
Fired when the SDK cache is cleared.
Event Detail: {} (empty object)
When it fires:
- After
window.sesamy.clearCache()is called - After purchases
- After certain user attribute changes
Example:
window.addEventListener('sesamyJsClearCache', () => {
console.log('Cache cleared, data will be refreshed');
// Reload entitlements or other cached data
refreshContentAccess();
});Common use cases:
- Trigger data refresh
- Debug caching issues
- Coordinate cache invalidation
- Update dependent systems
Event Patterns
Initialization Flow
// 1. Auth system initializes
window.addEventListener('sesamyJsAuthInitialized', () => {
console.log('1. Auth initialized');
});
// 2. Full SDK ready
window.addEventListener('sesamyJsReady', () => {
console.log('2. SDK ready');
});
// 3. User authenticated (if logged in)
window.addEventListener('sesamyJsAuthenticated', () => {
console.log('3. User authenticated');
});Login/Logout Cycle
// User logs in
window.addEventListener('sesamyJsAuthenticated', (event) => {
console.log('Logged in as:', event.detail.email);
showUserProfile(event.detail);
});
// User logs out
window.addEventListener('sesamyJsLogout', () => {
console.log('Logged out');
hideUserProfile();
});Purchase Flow
// User clicks "Subscribe"
document.querySelector('#subscribe-btn').addEventListener('click', () => {
window.sesamy.checkout('item-sku-123');
});
// User completes purchase and returns
window.addEventListener('sesamyJsPurchase', async (event) => {
const { itemSrc } = event.detail;
// Show confirmation
alert('Purchase successful!');
// Verify access
const hasAccess = await window.sesamy.hasAccess(itemSrc);
if (hasAccess) {
// Unlock content
document.querySelector('.premium-content').classList.remove('locked');
}
});Tracking with Google Analytics
// Track all major events
window.addEventListener('sesamyJsAuthenticated', (event) => {
gtag('event', 'login', {
method: 'Sesamy',
user_id: event.detail.sub
});
});
window.addEventListener('sesamyJsLogout', () => {
gtag('event', 'logout');
});
window.addEventListener('sesamyJsPurchase', (event) => {
gtag('event', 'purchase', {
transaction_id: event.detail.itemSrc,
value: /* amount */,
currency: 'USD',
items: [{
item_id: event.detail.itemSrc,
item_name: /* product name */
}]
});
});Debugging Events
// Log all Sesamy events
const sesamyEvents = [
'sesamyJsReady',
'sesamyJsAuthInitialized',
'sesamyJsAuthenticated',
'sesamyJsLogout',
'sesamyJsPurchase',
'sesamyUserAttributeChanged',
'sesamyJsClearCache',
];
sesamyEvents.forEach((eventName) => {
window.addEventListener(eventName, (event) => {
console.log(`[${eventName}]`, event.detail);
});
});Best Practices
Always Wait for Ready
// ❌ Bad: Calling before ready
window.sesamy.auth.isAuthenticated(); // May fail
// ✅ Good: Wait for ready event
window.addEventListener('sesamyJsReady', async () => {
const isAuth = await window.sesamy.auth.isAuthenticated();
});Handle Authentication State
// ✅ Good: Comprehensive auth handling
let isUserAuthenticated = false;
window.addEventListener('sesamyJsReady', async () => {
isUserAuthenticated = await window.sesamy.auth.isAuthenticated();
updateUI();
});
window.addEventListener('sesamyJsAuthenticated', () => {
isUserAuthenticated = true;
updateUI();
});
window.addEventListener('sesamyJsLogout', () => {
isUserAuthenticated = false;
updateUI();
});
function updateUI() {
document.querySelector('.auth-status').textContent = isUserAuthenticated
? 'Logged In'
: 'Logged Out';
}Use Event Delegation
// ✅ Good: Single event handler for multiple updates
window.addEventListener('sesamyJsAuthenticated', (event) => {
// Update multiple UI components
updateHeader(event.detail);
updateSidebar(event.detail);
trackAnalytics(event.detail);
});TypeScript Support
All events include proper TypeScript types when using Sesamy JS with TypeScript:
import { Events } from '@sesamy/sesamy-js';
window.addEventListener(Events.AUTHENTICATED, (event: CustomEvent) => {
const { email, appState, sub } = event.detail;
// TypeScript knows the shape of event.detail
});Next Steps
- Authentication - Login, logout, and user management
- API Reference - Check entitlements and manage subscriptions
- Content Management - Implement paywalls and access control
- Analytics - Track user interactions