Skip to Content
🎉 New release with new features and improvements! V0.0.6 Release →

Auto Token Refresh

How refresh works

The SDK does not check JWT expiry before each request. Instead, the engine validates the access token on every call. When the token is expired but a refresh token is available, the engine silently refreshes the session and completes your original request.

For header-based clients (typical for mobile, server, or SPA apps using the SDK), configure:

  1. authFn or jwtToken — supplies the current access token (Authorization: Bearer …)
  2. refreshTokenFn or refreshToken — supplies the refresh token, sent as X-BSH-REFRESHTOKEN on each request
const bshEngine = new BshEngine({ host: 'https://your-instance.com', jwtToken: 'initial-access-token', refreshToken: 'refresh-token', });
const bshEngine = new BshEngine({ host: 'https://your-instance.com' }) .withAuth(async () => { const token = localStorage.getItem('accessToken'); if (!token) return null; return { type: 'JWT', token }; }) .withRefreshToken(async () => localStorage.getItem('refreshToken'));

When refresh succeeds during a request, the engine may return the new access token in response.meta.accessToken.

Persist the new access token

Use onTokenRefreshed (recommended):

const bshEngine = new BshEngine({ host: 'https://your-instance.com', jwtToken: accessToken, refreshToken, onTokenRefreshed: async (newAccessToken) => { localStorage.setItem('accessToken', newAccessToken); }, });

Or the fluent helper:

new BshEngine({ host: 'https://your-instance.com', jwtToken, refreshToken }) .withOnTokenRefreshed(async (newAccessToken) => { localStorage.setItem('accessToken', newAccessToken); });

Cookie-based sessions (browser login) refresh via bsh_access_token / bsh_refresh_token cookies instead of headers. See Custom Authentication — Cookie sessions.

With cookie sessions, the engine returns an error on mutating requests (POST, PUT, PATCH, DELETE, …) when X-XSRF-TOKEN is missing or does not match the XSRF-TOKEN cookie. Set the header to the cookie value on every non-safe method. The default SDK client adds it automatically for mutating calls when JWT or API key auth is not configured; custom clientFn implementations must do the same. CSRF is not required when using Authorization (JWT Bearer or API key). See Authentication API — cookie sessions.

Explicit refresh endpoint

You can still call POST /api/auth/refresh manually when building your own auth flow.