Skip to Content

Token API

⚡ 8 min read

The transcodes.token object manages authentication tokens and session state.


Methods

getCurrentUser()

Returns the current user from the JWT token payload. Does not make an API call.

transcodes.token.getCurrentUser(): Promise<User | null>

Returns: Promise<User | null> - The user object or null if not authenticated.

Example:

const user = await transcodes.token.getCurrentUser(); if (user) { console.log('Current user:', user.email); }

This method extracts user info from the JWT token. For the most up-to-date user data, use transcodes.user.get().


getAccessToken()

Returns the current access token. Automatically refreshes if expired.

transcodes.token.getAccessToken(): Promise<string | null>

Returns: Promise<string | null> - The access token or null if not authenticated.

Example:

const token = await transcodes.token.getAccessToken(); if (token) { // Use token for API calls fetch('https://api.example.com/data', { headers: { Authorization: `Bearer ${token}`, }, }); }

Do not validate the access token on the client. Always validate tokens on your server.


hasToken()

Synchronously checks if a token exists in storage.

transcodes.token.hasToken(): boolean

Returns: boolean - true if a token exists.

Example:

if (transcodes.token.hasToken()) { console.log('Token exists'); } else { console.log('No token found'); }

This is a synchronous method. Use isAuthenticated() for a more accurate async check.


hasPrivateKey()

Checks if a private key exists in IndexedDB. The private key is used to generate access tokens.

transcodes.token.hasPrivateKey(): Promise<boolean>

Returns: Promise<boolean> - true if a private key exists.

Example:

const hasKey = await transcodes.token.hasPrivateKey(); if (hasKey) { console.log('Private key exists'); } else { console.log('No private key - user needs to authenticate'); }

validateToken()

Synchronously validates the current token (checks existence and expiration).

transcodes.token.validateToken(): boolean

Returns: boolean - true if the token exists and is not expired.

Example:

if (transcodes.token.validateToken()) { console.log('Token is valid'); } else { console.log('Token is invalid or expired'); }

This is a synchronous method that only checks token validity. Use isAuthenticated() for a full async check that includes token refresh.


isAuthenticated()

Checks the current authentication status.

transcodes.token.isAuthenticated(): Promise<boolean>

Returns: Promise<boolean> - true if the user is authenticated.

Important: This method returns a Promise. Always use await!

Example:

// Correct usage const isAuth = await transcodes.token.isAuthenticated(); if (isAuth) { console.log('User is authenticated'); } else { console.log('User is not authenticated'); }

Common Mistake:

// WRONG - this will always be truthy (Promise object) if (transcodes.token.isAuthenticated()) { // This always runs! } // CORRECT - use await if (await transcodes.token.isAuthenticated()) { // This correctly checks auth status }

signOut()

Signs out the current user. Removes tokens and keys from storage.

transcodes.token.signOut(): Promise<void>

Returns: Promise<void>

Example:

async function handleSignOut() { try { await transcodes.token.signOut(); console.log('Signed out successfully'); window.location.href = '/'; } catch (error) { console.error('Sign out failed:', error); } }

Usage Examples

Complete Authentication Check

async function checkAuth() { // Check authentication status const isAuth = await transcodes.token.isAuthenticated(); if (!isAuth) { console.log('Not authenticated'); return null; } // Get access token for API calls const token = await transcodes.token.getAccessToken(); console.log('Access token available:', !!token); return token; }

Protected API Call

async function callProtectedAPI(endpoint) { const token = await transcodes.token.getAccessToken(); if (!token) { throw new Error('Not authenticated'); } const response = await fetch(`https://api.example.com${endpoint}`, { headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', }, }); if (!response.ok) { throw new Error(`API call failed: ${response.status}`); } return response.json(); }

Last updated on