Skip to content

Events & Token Handling

When a user successfully authenticates, the <spartan-login> widget:

  1. Stores the JWT in localStorage under the key spartan-token
  2. Dispatches a spartan-login CustomEvent 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);
});

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',
},
});
}

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;
}
}

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';
}

For applications where every page requires authentication, you can intercept 401 responses globally:

// Place in your app entry point — only for fully-authenticated apps
const { 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;
};