@bkper/web-auth
@bkper/web-auth
Framework-agnostic OAuth authentication SDK for Bkper API.
Installation
bun add @bkper/web-authnpm i -S @bkper/web-authpnpm add @bkper/web-authyarn add @bkper/web-authQuick Start
import { BkperAuth } from '@bkper/web-auth';
// Initialize client with callbacksconst auth = new BkperAuth({ onLoginSuccess: () => { console.log('User authenticated!'); loadUserData(); }, onLoginRequired: () => { console.log('Please sign in'); showLoginButton(); },});
// Initialize authentication flow on app loadawait auth.init();
// Get access token for API callsconst token = auth.getAccessToken();if (token) { fetch('/api/data', { headers: { Authorization: `Bearer ${token}` }, });}Handling Token Expiration
Access tokens expire and need to be refreshed. The recommended pattern is to handle authentication errors and retry:
async function apiRequest(url: string, options: RequestInit = {}) { // Add auth header const token = auth.getAccessToken(); options.headers = { ...options.headers, Authorization: `Bearer ${token}`, };
const response = await fetch(url, options);
// Handle expired token if (response.status === 403) { try { await auth.refresh(); options.headers = { ...options.headers, Authorization: `Bearer ${auth.getAccessToken()}`, }; return fetch(url, options); // Retry once } catch (error) { // Refresh failed - the onError callback will be triggered // Handle the error appropriately (e.g., redirect to login, show error message) throw error; } }
return response;}What’s Included
- Framework-agnostic OAuth authentication SDK for Bkper API
- Callback-based API for authentication events
- OAuth flow with in-memory token management
- Token refresh mechanism
- TypeScript support with full type definitions
How It Works
Session Persistence:
- Access tokens are stored in-memory (cleared on page refresh)
- Sessions persist via HTTP-only cookies (managed by Bkper’s authentication service)
- Call
init()on app load to restore the session from cookies
Security:
- HTTP-only cookies protect refresh tokens from XSS
- In-memory access tokens minimize exposure
TypeScript Support
This package is written in TypeScript and provides full type definitions out of the box. All public APIs are fully typed, including callbacks and configuration options.
import { BkperAuth, BkperAuthConfig } from '@bkper/web-auth';
const config: BkperAuthConfig = { onLoginSuccess: () => console.log('Authenticated'), onError: error => console.error('Auth error:', error),};
const auth = new BkperAuth(config);Browser Compatibility
This package requires modern web browsers with support for:
- Fetch API for HTTP requests
- Location API for login/logout redirects
The package uses standard web APIs and works in any JavaScript environment that supports modern browser features.