Events & Token Handling
The spartan-login event
Section titled “The spartan-login event”When a user successfully authenticates, the <spartan-login> widget:
- Stores the JWT in
localStorageunder the keyspartan-token - Dispatches a
spartan-loginCustomEvent on the element
const widget = document.querySelector('spartan-login');
widget.addEventListener('spartan-login', (event: CustomEvent) => { const { token, transactionID } = event.detail; console.log('Logged in!', token);});Accessing the token
Section titled “Accessing the token”After login, the JWT is available at any time:
const token = localStorage.getItem('spartan-token');Include it in all API requests to your backend:
async function apiFetch(path: string, options: RequestInit = {}) { const token = localStorage.getItem('spartan-token'); return fetch(path, { ...options, headers: { ...options.headers, ...(token ? { Authorization: `Bearer ${token}` } : {}), 'Content-Type': 'application/json', }, });}Reading JWT claims client-side
Section titled “Reading JWT claims client-side”For display purposes only (e.g., showing the user’s email in a nav bar), you can decode the JWT client-side without verification:
function getTokenClaims(): { sub: string; email: string; sectorID: string } | null { const token = localStorage.getItem('spartan-token'); if (!token) return null; try { const payload = JSON.parse(atob(token.split('.')[1])); // SpartanAuth nests custom claims under "Claims" const claims = payload.Claims || payload; return { sub: claims.sub, email: claims.email, sectorID: claims.sectorID, }; } catch { return null; }}Logging out
Section titled “Logging out”To log a user out, remove the token from localStorage and redirect to the login page:
function logout() { localStorage.removeItem('spartan-token'); window.location.href = '/login';}Handling 401 responses globally
Section titled “Handling 401 responses globally”For applications where every page requires authentication, you can intercept 401 responses globally:
// Place in your app entry point — only for fully-authenticated appsconst { fetch: originalFetch } = window;
window.fetch = async (...args) => { const response = await originalFetch(...args); if (!response.ok && response.status === 401) { localStorage.removeItem('spartan-token'); if (!window.location.pathname.startsWith('/login')) { window.location.href = '/login'; } } return response;};