Introduction
The BunBase TypeScript SDK works in any environment that supports fetch and WebSocket — browsers, Node.js, Bun, React Native, and Expo.
Installation
Section titled “Installation”bun install @bunbase/js -Enpm install @bunbase/js -Epnpm install @bunbase/js -Eyarn add @bunbase/js -Eimport { BunBaseClient } from "@bunbase/js";
const client = new BunBaseClient({ url: "https://your-bunbase-server.com",});The client is a singleton. Create one instance per app and import it wherever needed.
Singleton pattern
Section titled “Singleton pattern”import { BunBaseClient } from "@bunbase/js";
export const client = new BunBaseClient({ url: import.meta.env.BUNBASE_URL ?? "http://localhost:8080",});
// Restore persisted session on app loadconst at = localStorage.getItem("bb_at");const rt = localStorage.getItem("bb_rt");if (at && rt) client.auth.restoreSession(at, rt);
// Persist tokens on changeclient.auth.onAuthChange((session) => { if (session) { localStorage.setItem("bb_at", session.accessToken); localStorage.setItem("bb_rt", session.refreshToken); } else { localStorage.removeItem("bb_at"); localStorage.removeItem("bb_rt"); }});Import the client anywhere:
import { client } from "@/lib/bunbase";
const posts = client.collection<Post>("posts");Token persistence
Section titled “Token persistence”Tokens are stored in-memory by default. Persist them across page reloads:
// Restore on startupconst at = localStorage.getItem("bb_at");const rt = localStorage.getItem("bb_rt");if (at && rt) client.auth.restoreSession(at, rt);
// Save on changeclient.auth.onAuthChange((session) => { if (session) { localStorage.setItem("bb_at", session.accessToken); localStorage.setItem("bb_rt", session.refreshToken); } else { localStorage.removeItem("bb_at"); localStorage.removeItem("bb_rt"); }});For React Native, replace localStorage with AsyncStorage or a Keychain library. Call restoreSession after the async read resolves.
Automatic token refresh
Section titled “Automatic token refresh”The SDK intercepts 401 responses and automatically calls /auth/refresh before retrying the original request. Multiple concurrent 401s share a single refresh call — no duplicate requests.
If refresh fails, tokens are cleared, onAuthChange(null) fires, and the original call throws a BunBaseError with status 401.