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, and confirm it's you before a sensitive change (requireReverification) |
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 |
useEnterprise(workspaceId) | A workspace's enterprise single sign-on, and the IT admin's setup link |
useEnterpriseAudit(workspaceId, options?) | The company's audit trail for its admins, paged, with a CSV download, and WorkOS's export with company audit logs on |
useEnterprisePolicy(workspaceId, options?) | The company's access policy for its admins: session length, IP allowlist, break-glass people, sign-in methods without single sign-on, the app's team signing in as its people, its network, signing people out ({ outsideMethods: true } for the sessions outside the sign-in methods), each person's sessions with personSessions and endPersonSession, and resetPasskeys |
useEnterpriseLogStreams(workspaceId, options?) | The company's log streams to its SIEM: add, change, test, pause, rotate and remove, and its WorkOS stream, read only |
useEnterpriseInsights(workspaceId, days?, options?) | The company's people, sign-ins and refusals over 7, 30 or 90 days |
useEnterpriseAdmins(workspaceId, options?) | Who holds which company role: list, name one of its people with a role, change it, take it away |
useEnterpriseRoles(workspaceId, options?) | The company's roles, presets first: make, change and delete its own |
useEnterpriseGroups(workspaceId, options?) | The company's groups: people, linked identity provider groups, workspaces and a company role; make, change, delete |
useEnterpriseWorkOSRoles(workspaceId, options?) | The company's roles in WorkOS: in sync or what needs attention, the issues, Refresh from WorkOS and opening the Admin Portal where the IT admin assigns them. Which roles and groups are shown there is assignableInWorkOS on useEnterpriseRoles and useEnterpriseGroups |
useEnterpriseConnectedApps(workspaceId, options?) | The apps and agents the company's people connected, each one's people, and disconnecting them |
useEnterpriseAgentAccess(workspaceId, options?) | The identity provider the company trusts to approve agents (pending until proven), what to enter in Okta, its keys and token lifetime, and saving, checking, turning off and removing it (agents through a company's identity provider) |
useEnterpriseKeys(workspaceId, options?) | The company's API keys: list, make one (its secret answered once, to the caller), revoke |
useEnterpriseServiceAccounts(workspaceId, options?) | The company's service accounts: list, add, rename, delete with their keys |
useEnterpriseItContacts(workspaceId, options?) | The company's IT and security contacts, read from WorkOS, and openInWorkOS to open the Admin Portal where the IT team changes them (IT and security contacts) |
useEnterpriseManagedGroups(workspaceId, options?) | The groups the signed-in member manages, each with its people and whether they may change it now (group managers) |
useEnterpriseWorkspacePolicies(workspaceId, options?) | The stricter rules the company holds some of its workspaces to: read, save, remove, and the sessions a save will meet (stricter rules for one workspace) |
useStepUp(scope, options?) | Confirming it's you before a company change: guard sends the change and opens Confirm it's you on a 403 reauth_required, keeping the unsent change for the return (confirming it's you) |
useAccessRefused() | The refusal when a company's IP allowlist (ip_not_allowed) or its network (tenant_restricted, tenant_header_invalid) refused a request; the session is kept |
useSessionEnded() | Why a company's access policy ended the session (401 session_ended), as { ended, dismiss }, so your app can say it (when a company ends a session) |
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 |
useTrialEligibility(workspaceId) | Whether the signed-in person would get a trial here, and on which plans (SDK 1.0.0 and later) |
useConvertToPaid(workspaceId) | End a trial now and pay with the card on file; paymentUrl when the card needs more (SDK 1.0.0 and later) |
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 |
Note
The enterprise hooks (useEnterprise, useEnterpriseAudit, useEnterprisePolicy, useEnterpriseLogStreams, useEnterpriseInsights, useEnterpriseAdmins, useEnterpriseRoles, useEnterpriseGroups, useEnterpriseWorkOSRoles, useEnterpriseConnectedApps, useEnterpriseAgentAccess, useEnterpriseKeys, useEnterpriseServiceAccounts, useEnterpriseItContacts, useEnterpriseManagedGroups, useEnterpriseWorkspacePolicies), useStepUp, useAccessRefused, useSessionEnded, useTrialEligibility and useConvertToPaid: Requires @buildbase/sdk 1.0.0 or later. requireReverification and the session's authTime on useSaaSAuth() are in 0.0.90 and later.
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 |
usePreviewSubscriptionChange() | What a plan change costs before it is made |
useUpcomingInvoice() | The next invoice: amount, date and lines |
useCancelSubscription() | Cancel immediately or at period end |
useResumeSubscription() | Undo a scheduled cancellation |
Note
usePreviewSubscriptionChange and useUpcomingInvoice: Requires @buildbase/sdk 1.0.0 or later. @buildbase/sdk 0.0.90 has the other four.
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 |
useEnterpriseApi() | Imperative enterprise SSO client |
useUploadsApi() | Imperative uploads client (UploadsApi) |
Note
useEnterpriseApi: Requires @buildbase/sdk 1.0.0 or later.
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. For limits and refusals, see:
100+ 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 |
EnterpriseAccess | Single sign-on status for a workspace, with the IT admin's setup |
EnterpriseItContacts | The company's IT and security contacts, read only, with Change in WorkOS for those who manage setup; shown inside EnterpriseAccess |
EnterpriseActivity | The company's activity for its admins: sign-ins, refusals, provisioning and setup, with a CSV download, and with company audit logs on, WorkOS's export and audit log viewer |
EnterpriseSecurity | The company's access policy for its admins, with the sign-in methods card, signing one person or everyone out, and Confirm it's you before a change |
EnterpriseLogStreams | The company's log streams to its SIEM, with delivery state, a test event, pause and resume, and the signing secret shown once; with company audit logs on, its WorkOS stream, read only |
EnterpriseInsights | The company's identity insights: people, sign-ins, refusals by reason, day by day |
EnterpriseAdmins | Who holds which company role, named in the app or by the identity provider, with giving, changing and taking roles away |
EnterpriseRoles | The company's roles, area by area, with making, changing and deleting its own |
EnterpriseGroups | The company's groups, with the people, identity provider groups, workspaces and company role each gives, and making, changing and deleting them |
EnterpriseWorkOSRoles | The company's Roles in WorkOS section: how its roles stand in WorkOS, the issues for those who manage company roles, Refresh from WorkOS and Assign roles in WorkOS |
EnterpriseConnectedApps | The apps and agents the company's people connected, with disconnecting one person or everyone |
EnterpriseAgentAccess | The company's Agents approved by your identity provider card: the issuer (Pending until proven), what to enter in Okta with copy buttons, the token lifetime, Check, Turn off and Remove, and Confirm it's you before saving an issuer or turning it back on |
EnterpriseApiKeys | The company's API keys and service accounts: making a key with its scopes, lifetime and addresses, the secret shown once, revoking |
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 | 18 screens: profile, security, devices, billing, account-credits, connected-agents, my-selling, general, users, subscription, usage, credits, features, notifications, permissions, enterprise, selling, 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.
Note
The enterprise screens (EnterpriseAccess, EnterpriseItContacts, EnterpriseActivity, EnterpriseSecurity, EnterpriseLogStreams, EnterpriseInsights, EnterpriseAdmins, EnterpriseRoles, EnterpriseGroups, EnterpriseWorkOSRoles, EnterpriseConnectedApps, EnterpriseAgentAccess, EnterpriseApiKeys): Requires @buildbase/sdk 1.0.0 or later.
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 { response } = useSubscriptionContext();
return (
<WhenPermission permission={Permission.WORKSPACE_BILLING_VIEW}>
<span>{response?.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 |
bb.enterprise | A workspace's enterprise SSO with a member's session: status (with the company's IT and security contacts, read from WorkOS), setup link (from @buildbase/sdk 1.0.0, { purpose: 'it_contacts' } opens the Admin Portal page where the company's IT team changes those contacts), the company's audit trail, its CSV and WorkOS export, access policy, people and signing out, one person's sessions and ending one, log streams, insights and agent access |
Note
bb.enterprise: Requires @buildbase/sdk 1.0.0 or later.
The enterprise routes your team's console and a company's own tools call are listed with each feature, not here. The company's IT and security contacts, for example, are GET /api/auth/enterprise/enterprises/<enterprise id>/it-contacts in the console and GET /api/v1/company/it-contacts with admins:read in the company API, both read only.
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.
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.
Server client (@buildbase/sdk/server)
createServerClient({ serverUrl, apiToken }) is the client for your own backend. It takes an org API token, never a person's session, and runs only on a server.
- Since
@buildbase/sdk0.0.73 it reads published content: blogs, docs, FAQs, testimonials, rich content and collections (Delivering content). - From
@buildbase/sdk1.0.0 it also hasemails.sendandemails.get(Sending email), andsubscribers.upsert,get,unsubscribe,resubscribeanddelete(Subscribers).
@buildbase/sdk/server/next adds Next's tag cache and a revalidateTag webhook route for the content reads, so cached content refreshes when it changes: withNextCache, createNextWebhookHandler and nextFetchOptions (Next.js data cache).
Environments
environment on BuildBase(), SaaSOSProvider, createAgentStack and BuildBaseTracking names one of your development or staging environments. environmentId(orgId, environment) returns the id the HTTP API knows it by: <orgId>-<key>, or the org id itself in production. PRODUCTION_ENVIRONMENT is 'production'. Requires @buildbase/sdk 1.0.0 or later. The buildbase commands are in the buildbase CLI.
Note
environmentId() and PRODUCTION_ENVIRONMENT: Requires @buildbase/sdk 1.0.0 or later.
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). From @buildbase/sdk 1.0.0 it also exports:
McpToolErrorandmcpInputRequired(): errors an agent can act on, and asking the user a question mid-call.defineSearchFetchTools(): thesearchandfetchpair ChatGPT's deep research calls.fetchPublicUrl(): fetch a URL an agent gave you without letting it reach your private network.buildMcpInstallLinks(): install links for every MCP client.directoryToolsets(tools): works out theclaudeandchatgpttoolsets from your tools (the handler adds both by itself).
buildServerCard() and buildAiCatalog() come from @buildbase/sdk, with the rest of agent discovery. They build the server card (a short description of your MCP server that directories read, defined by the MCP proposal SEP-2127) and the AI Catalog.
For setup, token minting and the user-facing side, see MCP and agents; for connecting each client, Connect an AI agent; for agents a company's identity provider approves (grantType: "id_jag" and expiresInMax at your token URL), see agents through a company's identity provider.
Note
McpToolError, mcpInputRequired(), defineSearchFetchTools(), fetchPublicUrl(), buildMcpInstallLinks(), directoryToolsets, buildServerCard() and buildAiCatalog(): Requires @buildbase/sdk 1.0.0 or later.
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(), WEBHOOK_EVENTS and isWebhookEvent() - every event name the server sends. From 1.0.0, verifyStandardWebhook() and parseStandardWebhookEvent() for the Standard Webhooks headers, an open format for signing webhooks that many providers share |
| Enterprise | enterpriseSsoAvailable(), enterpriseProvisioningAvailable() (from @buildbase/sdk/react) - whether to show the Single sign-on screen and its directory card; onAccessRefused() and isAccessRefused() - a company's IP allowlist or network refusing a request, outside React; onSessionEnded(), isSessionEnded() and sessionEndedCopy() - a session the company ended, and why, outside React; isReauthRequired() (from @buildbase/sdk/react) - a change that needs a recent sign-in, with the ReauthRequiredError type; useEnterpriseItContacts() and <EnterpriseItContacts /> - the company's IT and security contacts; useEnterpriseManagedGroups() - the groups a member manages; useEnterpriseWorkspacePolicies() - stricter rules for one workspace; useStepUp() - confirming it's you before a company change |
| 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 |
Note
In the Enterprise row, everything except isReauthRequired() and ReauthRequiredError (enterpriseSsoAvailable(), enterpriseProvisioningAvailable(), onAccessRefused(), isAccessRefused(), onSessionEnded(), isSessionEnded(), sessionEndedCopy(), useEnterpriseItContacts(), <EnterpriseItContacts />, useEnterpriseManagedGroups(), useEnterpriseWorkspacePolicies() and useStepUp()): Requires @buildbase/sdk 1.0.0 or later.
Note
In the Webhooks row, verifyStandardWebhook() and parseStandardWebhookEvent(): Requires @buildbase/sdk 1.0.0 or later.
Full reference
For complete parameters, return types, TypeScript interfaces, and code examples for every export, see the SDK README on npm.