Step 5: Listen for State Changes
⏱ 5 min readReact to authentication state changes in real-time.
Auth State Changed Event
Listen for authentication state changes:
transcodes.on('AUTH_STATE_CHANGED', (payload) => {
if (payload.isAuthenticated) {
console.log('User logged in:', payload.user.email);
} else {
console.log('User logged out');
}
});This image shows the TypeScript definitions (.d.ts file) that enable type-safe programming with the framework:

Event Payload
{
isAuthenticated: boolean;
user?: {
id: string;
email: string;
createdAt: string;
};
}All Available Events
| Event | When Fired | Payload |
|---|---|---|
AUTH_STATE_CHANGED | Login, logout, or initial auth check | { isAuthenticated, user? } |
TOKEN_REFRESHED | Access token automatically renewed | { token } |
TOKEN_EXPIRED | Token expired (before refresh) | { expiredAt } |
ERROR | Authentication error occurred | { error, message } |
Token Refresh Event
Listen for automatic token refreshes:
transcodes.on('TOKEN_REFRESHED', (payload) => {
console.log('New token available:', payload.token);
// Update your API client with new token
});Error Event
Handle authentication errors:
transcodes.on('ERROR', (payload) => {
console.error('Auth error:', payload.message);
// Show error message to user
});Framework Integration
React
// React Hook
import { useState, useEffect } from 'react';
function useAuth() {
const [user, setUser] = useState(null);
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
const handleAuthChange = (payload) => {
setIsAuthenticated(payload.isAuthenticated);
setUser(payload.user || null);
};
transcodes.on('AUTH_STATE_CHANGED', handleAuthChange);
// Cleanup
return () => {
transcodes.off('AUTH_STATE_CHANGED', handleAuthChange);
};
}, []);
return { user, isAuthenticated };
}
// Usage
function App() {
const { user, isAuthenticated } = useAuth();
return (
<div>
{isAuthenticated ? <p>Welcome, {user.email}!</p> : <p>Please sign in</p>}
</div>
);
}Check Current Auth Status
Get the current authentication status without waiting for events:
async function checkAuth() {
const isAuth = await transcodes.token.isAuthenticated();
if (isAuth) {
const user = await transcodes.token.getCurrentUser();
console.log('Current user:', user);
}
}Sign Out
Sign out the current user:
await transcodes.token.signOut();
// AUTH_STATE_CHANGED event will fire with isAuthenticated: falseRemove Event Listeners
Clean up event listeners when no longer needed:
const handler = (payload) => {
console.log('Auth changed:', payload);
};
// Add listener
transcodes.on('AUTH_STATE_CHANGED', handler);
// Remove listener
transcodes.off('AUTH_STATE_CHANGED', handler);What’s Next
Event handling complete! Next step: - Step 6: Server-Side Integration - Secure your backend - Option: Auth Console Panel - No-code solution
Last updated on