API Reference
Full SDK reference - all hooks, components, types, and server methods.
The complete API reference with every parameter, return type, and code example lives in the SDK README on npm. This page summarizes what's available and when to use each part.
React SDK (@buildbase/sdk/react)
Hooks
| Hook | When to use |
|---|---|
useSaaSAuth() | Sign in/out, get current user, check auth status, open settings |
useSessions() | List and revoke the signed-in user's active sessions |
useDevices() | List, rename, sign out, or forget the user's devices |
useGuestUpgrade() | Turn a guest into an account: an address, then a 6-digit code |
useConnectedAgents() | List and disconnect AI agents connected to the user's account |
useMcpConnection() | Read the MCP connection config for building a custom connect guide |
useSaaSWorkspaces() | List, create, switch, update, delete workspaces |
useSubscription() | Get current plan, status, billing interval |
useTrialStatus() | Check trial state - isTrialing, daysRemaining, isTrialEnding |
useSeatStatus() | Check seat limits - memberCount, canInvite, inviteBlockReason |
useCreditBalance() | Get credit balance - available, totalConsumed, totalGranted |
useConsumeCredits() | Deduct credits with idempotency |
usePurchaseCredits() | Open Stripe checkout for credit packages |
useExpiringCredits() | Get credits expiring within N days |
useQuotaUsageStatus() | Get one quota's usage - consumed, included, available |
useAllQuotaUsage() | Get all quotas at once |
useRecordUsage() | Record usage against a quota |
usePermissions() | Check permissions - can(), isOwner, role |
useTranslation() | i18n - t(), locale, dir, fmtCents(), fmtNum() |
usePushNotifications() | Subscribe/unsubscribe to browser push |
useUserAttributes() | Get/update custom user attributes |
useUserFeatures() | Check user-level feature flags |
usePublicPlans() | Fetch plans without authentication (for public pricing pages) |
useCreateCheckoutSession() | Create a Stripe Checkout session |
useInvoices() | Paginated invoice history |
useInvoice() | One invoice by id |
useBillingPortal() | Get Stripe billing portal URL |
useUpload(purpose) | Upload a workspace image or profile picture - see below |
Subscription management
Changing a subscription is separate from reading one. useSubscription() reads;
these mutate.
| Hook | When to use |
|---|---|
useSubscriptionManagement() | Combined upgrade, downgrade, cancel and resume state |
useUpdateSubscription() | Change plan or billing interval |
useCancelSubscription() | Cancel immediately or at period end |
useResumeSubscription() | Undo a scheduled cancellation |
Plans, credits and usage data
| Hook | When to use |
|---|---|
usePlanGroup() | One plan group with its versions |
usePlanGroupVersions() | Version history for a plan group |
usePublicPlanGroupVersion() | A plan group version without authentication |
useCreditPackages() | Purchasable credit packages |
usePublicCreditPackages() | Credit packages without authentication |
useCreditTransactions() | Paginated credit ledger |
useUsageLogs() | Raw usage records behind a quota |
Context and lower-level hooks
The *Context hooks read state a provider already fetched, so they do not
trigger a request of their own. The *Api hooks expose the imperative client
behind the data hooks - reach for them only when the data hook does not fit.
| Hook | Purpose |
|---|---|
useSaaSOs() | The SDK instance and its configuration |
useSaaSSettings() | Org settings resolved for the current app |
useUIConfig() | Merged UI configuration |
useUIVisibility() | Whether a given UI element should render |
useFullScreenLoader() | Show or hide the SDK's full-screen loader |
useSubscriptionContext() | Subscription state from SubscriptionContextProvider |
useCreditBalanceContext() | Balance from CreditBalanceContextProvider |
useQuotaUsageContext() | Quota state from QuotaUsageContextProvider |
useDevicesApi() | Imperative devices client |
useSessionsApi() | Imperative sessions client |
useConnectedAgentsApi() | Imperative connected-agents client |
useUploadsApi() | Imperative uploads client (UploadsApi) |
Uploads
From @buildbase/sdk
0.0.84,
useUpload(purpose) uploads one image for a signed-in user, straight to
storage, where it counts against your organization's storage. purpose is
'workspace-image' or 'profile-image'. It returns:
| Field | What it is |
|---|---|
upload | (file) => Promise<IUploadedFile>: resolves with { id, name, size, mimeType, url, width, height } |
cancel | Aborts the upload in flight |
loading | true while an upload runs |
error | Why the last upload failed, as a sentence in the active locale, or null |
failure | The same as a reason - tooLarge, invalid, disabled, userLimit, unavailable, failed |
enabled | Whether your organization lets its users upload |
maxBytes | The largest file your organization allows |
maxLabel | maxBytes as a reader reads it, in their locale: "5 MB" |
enabled and maxBytes come from the end-user upload settings in the console;
hide or limit the control with them rather than waiting for a refusal. The
stored file's url is public: save it as the workspace's image or the user's
profile picture. Limits and refusals: Uploads by your app's
users and Error
codes.
40+ hooks total. See the full hook reference for parameters and return types.
Conditional components
Wrap UI in these - the SDK shows or hides children based on state. No if-statements needed.
| Component | Shows children when... |
|---|---|
WhenAuthenticated / WhenUnauthenticated | User is / isn't signed in |
WhenRoles / WhenWorkspaceRoles | User has specific role(s) |
WhenPermission | User has specific permission(s) |
WhenSubscription / WhenNoSubscription | Workspace has / lacks a subscription |
WhenSubscriptionToPlans | Subscribed to specific plan slug(s) |
WhenTrialing / WhenNotTrialing / WhenTrialEnding | Trial state matches |
WhenQuotaAvailable / WhenQuotaExhausted / WhenQuotaOverage / WhenQuotaThreshold | Quota usage matches condition |
WhenCreditsAvailable / WhenCreditsExhausted / WhenCreditsLow | Credit balance matches condition |
WhenWorkspaceFeatureEnabled / WhenWorkspaceFeatureDisabled | Workspace feature flag state |
WhenUserFeatureEnabled / WhenUserFeatureDisabled | User feature flag state |
20+ components total.
Pre-built pages and screens
| Component | What it renders |
|---|---|
PricingPage | Full pricing page with plan cards, interval toggle, Stripe checkout |
CreditStorePage | Credit package store with pricing and purchase |
CreditBalance | Current balance, ready to drop in a header or sidebar |
WorkspaceSwitcher | Dropdown with search, create, and switch |
Devices / Sessions | Device and session lists with sign-out controls |
ConnectedAgents | AI agents connected to the account, with disconnect |
ConnectMcpGuide | Generated instructions for connecting an agent over MCP |
BetaForm | Beta signup/waitlist form |
GuestUpgrade | A guest's "Create your account" form |
ImpersonationBanner | The bar shown while an app owner is signed in as the user. SaaSOSProvider renders it already |
| Workspace settings dialog | 13 screens: profile, security, devices, connected-agents, general, users, subscription, usage, credits, features, notifications, permissions, danger |
The settings dialog is not a standalone component - open it with openWorkspaceSettings(section), returned by useSaaSAuth(). Pass a SettingsScreen value (e.g. SettingsScreen.Devices) to open a specific screen.
Providers
SaaSOSProvider (also exported as BuildBaseProvider) is the only required
one. The rest are opt-in: mount a context provider once high in the tree, then
read it with the matching *Context hook instead of refetching per component.
| Provider | Enables |
|---|---|
SaaSOSProvider | Everything. Required at the app root |
SubscriptionContextProvider | useSubscriptionContext() |
CreditBalanceContextProvider | useCreditBalanceContext() |
CreditActionsProvider | Credit consume and purchase actions |
QuotaUsageContextProvider | useQuotaUsageContext() |
PushNotificationProvider | Already inside SaaSOSProvider; nest one only for another worker path |
Layout helpers
Presentational components the SDK uses internally and re-exports so your own
screens can match: EmptyState, LoadingState, FullScreenLoader,
SectionHeader, StatusBanner, SidebarNavItem, SidebarNavSection.
Putting it together
SaaSOSProvider takes serverUrl, version, orgId and an auth block - see
Installation for the full configuration. Once it is
mounted, context providers nest inside it, and their hooks read that state
without issuing a request of their own:
import {
Permission,
SubscriptionContextProvider,
useSubscriptionContext,
WhenPermission,
} from '@buildbase/sdk/react';
// Inside <SaaSOSProvider>, mount the context once...
function BillingArea({ children }: { children: React.ReactNode }) {
return <SubscriptionContextProvider>{children}</SubscriptionContextProvider>;
}
// ...then read it anywhere below, with no extra fetch per component.
function PlanBadge() {
const { subscription } = useSubscriptionContext();
return (
<WhenPermission permission={Permission.WORKSPACE_BILLING_VIEW}>
<span>{subscription?.plan?.name ?? 'No plan'}</span>
</WhenPermission>
);
}Server SDK (@buildbase/sdk)
See Server SDK for method signatures and examples. Key namespaces:
| Namespace | What it does |
|---|---|
bb.subscription | Get, checkout, update, cancel, resume subscriptions |
bb.credits | Balance, consume, purchase, packages, transactions |
bb.usage | Record usage, batch recording, quota status |
bb.workspace | CRUD workspaces |
bb.users | List, invite, remove, update roles, profile |
bb.notification | Send email + push notifications |
bb.plans | Get plan groups and versions |
bb.invoices | List and get invoices |
bb.features | List and toggle feature flags |
bb.permissions | Check and resolve permissions for any user - both methods take an explicit userId |
Regional server URL
An app that serves many organizations cannot bake one serverUrl into its
build. Two server-side functions, exported from @buildbase/sdk
0.0.84
and later, look it up:
| Function | What it does |
|---|---|
resolveServerUrl({ orgId, centralUrl, apiKey }) | Asks BuildBase where the organization lives and answers { orgId, region, cellId, serverUrl }, cached for as long as BuildBase says, an hour at most |
clearResolvedServerUrl({ orgId, centralUrl }) | Forgets the cached answer for one organization |
centralUrl is https://central.console.buildbase.app{/* @endstat */}.
Pass the organization's API key as apiKey: without it every id resolves to the
default region, on purpose, so an EU organization would quietly be sent to the
default one. resolveServerUrl throws on a failed lookup rather than guessing.
When a server answers 421, the cached answer is stale: call
clearResolvedServerUrl, resolve again and retry the request once. Both also
take cache, a store with get, set and optionally delete, to share
answers between processes; the default is in memory.
Data exports (@buildbase/sdk/data)
Reference data with no React dependency:
countries- country list with codes and flagscurrencies- currency codes, symbols, and nameslanguages- language codes and namestimezones- IANA timezone list
Tracking (@buildbase/sdk/tracking)
The analytics and ad tags configured under Settings › Tracking & tags, installed by the SDK. Inside SaaSOSProvider pass the tracking prop; on a page without the provider tree, such as a marketing site, wrap it in <BuildBaseTracking>. See Tracking & Tags.
| Export | What it does |
|---|---|
<BuildBaseTracking> | Loads your tags and captures attribution without the rest of the provider tree |
useTracking() | track() a canonical or custom event, and read or set consent from your cookie banner |
useCheckoutCompleted() | Fires purchase once on the page Stripe returns to |
getAttribution() | The stored ad click id and campaign for this visitor |
EVENT_MAPPINGS | How each canonical event is named for GA4, Meta, TikTok and Reddit |
FUNNEL_EVENTS | The funnel events the SDK's own components emit (pricing viewed, plan picker opened, gate shown, ...) |
TAG_PROVIDERS | The supported tag providers and the id each one needs |
MCP toolkit (@buildbase/sdk/mcp)
Server-side, framework-agnostic toolkit that turns your app into an MCP (Model Context Protocol) server, so AI agents can operate its BuildBase capabilities. Key exports: createMcpHandler() (stateless Streamable HTTP handler), defineMcpTool() / defineMcpResource() / defineMcpPrompt() (custom capabilities), builtinMcpTools and selectBuiltinTools() (ready-made BuildBase tools), buildbaseAuth() (Bearer-token verification for agent requests), and createAgentStack() (MCP server plus agent-discovery routes from one config). For setup, token minting and the user-facing side, see MCP and agents.
Utilities (re-exported from core)
| Category | Key exports |
|---|---|
| Billing math | calculateTotalSubscriptionCents(), getBasePriceCents(), getPerSeatPriceCents(), getSeatPricing() |
| Currency | formatCents(), getCurrencySymbol(), getCurrencyFlag(), getPricingVariant() |
| Permissions | Permission.* constants, hasPermission(), resolvePermissions() |
| Webhooks | parseWebhookEvent(), verifyWebhookSignature() |
| Auth intent | saveAuthIntent(), consumeAuthIntent() - preserve redirect across auth flow |
| Account | isReauthRequired(), isReadOnlySession(), isValidUsername(), normaliseUsername(), connectWallet() |
| Events | eventEmitter - SDK event bus for cross-component communication |
| Validation | validateInvite() - check seat limits before inviting |
Full reference
For complete parameters, return types, TypeScript interfaces, and code examples for every export, see the SDK README on npm.