Skip to content
BunBase BunBase BunBase Docs Alpha v0.1.0

Introduction

The BunBase TypeScript SDK works in any environment that supports fetch and WebSocket — browsers, Node.js, Bun, React Native, and Expo.

Terminal window
bun install @bunbase/js -E
import { 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.

src/lib/bunbase.ts
import { BunBaseClient } from "@bunbase/js";
export const client = new BunBaseClient({
url: import.meta.env.BUNBASE_URL ?? "http://localhost:8080",
});
// Restore persisted session on app load
const at = localStorage.getItem("bb_at");
const rt = localStorage.getItem("bb_rt");
if (at && rt) client.auth.restoreSession(at, rt);
// Persist tokens on change
client.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");

Tokens are stored in-memory by default. Persist them across page reloads:

// Restore on startup
const at = localStorage.getItem("bb_at");
const rt = localStorage.getItem("bb_rt");
if (at && rt) client.auth.restoreSession(at, rt);
// Save on change
client.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.

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.