Skip to Content

setAuthToken, getAuthToken

Two low-level functions that write and read the JWT sent with every API call. You usually use signIn and signOut instead.

Usage

app/kiosk/page.tsx
import { setAuthToken, getAuthToken } from "app/hooks"; // A token from your own API, without user details async function startKiosk(code: string) { const { token } = await api.kiosk.session({ code }); setAuthToken(token); } const hasToken = getAuthToken() !== null;

Signature

app/hooks.ts
function setAuthToken(token: string | null): void; function getAuthToken(): string | null;

Parameters

  • token (setAuthToken): the JWT to store. Pass null to clear it.

Returns

setAuthToken returns nothing. The token is stored in the browser; from then on every request through useApiClient() and useApi() sends Authorization: Bearer <token>. When the browser blocks storage (private mode), the token lasts until the page reloads.

getAuthToken returns the current token, or null.

Examples

setAuthToken stores only the token. It doesn’t store the user and doesn’t make useSession re-render. When the sign-in API returns { token, user }, use signIn:

app/login/page.tsx
signIn(await api.auth.login(values)); // instead of setAuthToken(res.token)

Don’t add the Authorization header yourself and don’t write the token to localStorage yourself.

Next steps

Last updated