Server SDK overview
Node.js SDK for backend operations - usage recording, credit consumption, notifications, and more.
The server SDK lets you call BuildBase from your backend - record usage, consume credits, check subscriptions, send notifications, and manage workspaces.
import BuildBase from '@buildbase/sdk';
const bb = BuildBase({
serverUrl: 'https://api.console.buildbase.app',
orgId: 'your-org-id',
getSessionId: async () => {
const cookies = await getCookies();
return cookies.get('bb-session-id')?.value ?? null;
},
});To talk to one of your development or staging environments instead of production, pass its key as environment. Leave it unset for production. Requires @buildbase/sdk 1.0.0 or later. A route that calls the HTTP API itself addresses the environment with environmentId(orgId, environment) from the same release (From your own server routes).
const bb = BuildBase({
serverUrl: process.env.NEXT_PUBLIC_BUILDBASE_SERVER_URL!,
orgId: process.env.NEXT_PUBLIC_BUILDBASE_ORG_ID!,
environment: process.env.NEXT_PUBLIC_BUILDBASE_ENVIRONMENT,
getSessionId: async () =>
(await getCookies()).get('bb-session-id')?.value ?? null,
});Common patterns
Record usage and enforce quotas
export async function POST(req) {
const usage = await bb.usage.record(workspaceId, {
quotaSlug: 'api-calls',
quantity: 1,
// A string, or left out: a null key is refused with 400.
idempotencyKey: req.headers.get('x-request-id') ?? undefined,
});
if (usage.available <= 0) {
return Response.json({ error: 'Quota exceeded' }, { status: 429 });
}
return Response.json({ remaining: usage.available });
}Consume credits
try {
await bb.credits.consume(workspaceId, {
amount: 10,
description: 'AI generation',
});
} catch (err) {
if (err.code === 'INSUFFICIENT_CREDITS') {
return Response.json({ error: 'Not enough credits' }, { status: 402 });
}
}Check subscription
const { subscription, plan } = await bb.subscription.get(workspaceId);
// A trial is a subscription in good standing: let it through. So is
// past_due: the subscription stays usable while the payment retries run.
const allowed = ['active', 'trialing', 'past_due'];
if (!subscription || !allowed.includes(subscription.subscriptionStatus)) {
return Response.json({ error: 'Subscription required' }, { status: 403 });
}Send notifications
await bb.notification.send(workspaceId, 'comment-added', userId, {
title: 'New comment',
message: 'Someone commented on your post.',
url: '/posts/123',
});Background jobs with withSession()
In API routes, getSessionId reads the session from the request. For background jobs or cron tasks with no request context, use withSession():
const api = bb.withSession(serviceAccountSessionId);
await api.credits.consume(workspaceId, { amount: 50 });
await api.notification.send(workspaceId, 'job-completed');Method reference
bb.subscription
| Method | Parameters | Returns | Description |
|---|---|---|---|
get(workspaceId) | string | { subscription, plan, planVersion, group, groupVersion } | Get active subscription and plan details |
checkout(workspaceId, options) | string, { planVersionId, billingInterval?, currency?, successUrl?, cancelUrl? } | { type, checkoutUrl, sessionId } | Create a Stripe Checkout session. type is always checkout; redirect to checkoutUrl. Trials also go through Checkout, so the customer's card is on file when the trial ends |
update(workspaceId, options) | string, { planVersionId, billingInterval?, successUrl?, cancelUrl?, prorationDate? } | Updated subscription | Change plan (upgrade/downgrade with proration) |
preview(workspaceId, options) | string, { planVersionId, billingInterval?, currency? } | { kind, dueToday, nextInvoice, effectiveAt, prorationDate, ... } | What a plan change costs before it is made. Writes nothing; pass prorationDate to update |
getUpcomingInvoice(workspaceId) | string | { kind, amount, date, currency, lines } | The next invoice as Stripe would cut it now; kind: 'none' when cancelling at the period end, and kind: 'paused' with resumesAt (null for a pause with no end date) while a pause is scheduled or in force |
cancel(workspaceId) | string | Same shape as get() | Cancel at period end |
resume(workspaceId) | string | Same shape as get() | Reverse a pending cancellation |
getBillingPortalUrl(workspaceId, returnUrl?) | string, string? | { url } | Stripe billing portal link |
Note
preview, getUpcomingInvoice and the prorationDate option of update: Requires @buildbase/sdk 1.0.0 or later. @buildbase/sdk 0.0.90 has get, checkout, update, cancel, resume and getBillingPortalUrl.
get answers subscription.hasPaymentMethod: true when a payment method is on file for the Stripe subscription, false when none is, and absent when the server cannot tell (no Stripe subscription). It, and the paused kind of getUpcomingInvoice, come from the BuildBase server of this release; an older server leaves hasPaymentMethod out and never answers paused. The typings for both are in SDK 1.0.0 and later.
Currency. checkout, preview and every plan change bill in the currency the workspace is already locked to (its subscription, or the billing currency it pays in), else the currency you pass, else the first of your organization's billing currencies that the plan is priced in. The organization's list is stored in alphabetical order, so the first is the alphabetically first one, not the one added first. A plan with no price in that currency is refused with 400 PLAN_CURRENCY_UNAVAILABLE, and a currency other than the one the workspace is locked to with 400 SUBSCRIPTION_CURRENCY_MISMATCH. See Error codes.
bb.entitlements
| Method | Parameters | Returns | Description |
|---|---|---|---|
get({ workspaceId }) | { workspaceId } | The workspace's entitlement, or null on an older server | What the workspace may do, as the server composed it. Any member's session is answered |
check({ workspaceId, slug, current?, wanted? }) | { workspaceId, slug, current?, wanted?, strictAbsent? } | { kind, state, allowed, limit, remaining, source, standing, ... } | One slug, answered as useEntitlement answers it. See Entitlement Checks |
Note
bb.entitlements: Requires @buildbase/sdk 1.0.0 or later. On 0.0.90 and earlier, read the workspace's plan with bb.subscription.get.
bb.credits
| Method | Parameters | Returns | Description |
|---|---|---|---|
getBalance(workspaceId) | string | { available, totalGranted, totalConsumed, totalExpired, totalRefunded } | Current credit balance |
consume(workspaceId, options) | string, { amount, description?, idempotencyKey? } | { success, consumed, balanceAfter } | Deduct credits. Throws INSUFFICIENT_CREDITS (402) if balance too low |
purchase(workspaceId, options) | string, { creditPackageId, currency?, successUrl, cancelUrl } | { sessionId, url } - Stripe Checkout URL | Buy a credit package |
getPackages(workspaceId) | string | CreditPackage[] | List available credit packages |
getPublicPackages() | - | { packages, notes? } | List credit packages without auth (for public store pages) |
getTransactions(workspaceId, query?) | string, { type?, page?, limit? }? | { docs, totalDocs, page, totalPages, ... } - paginated | Credit history (purchases, consumption, grants) |
getExpiring(workspaceId, days?) | string, number? | { days, expiringCredits, buckets } | Credits expiring within days (default 7) |
bb.addOns
| Method | Parameters | Returns | Description |
|---|---|---|---|
list(workspaceId, options?) | string, { currency? }? | { currency, locked, offers } | The add-ons on sale to the workspace, what it holds and purchasable |
purchase(workspaceId, request) | string, { offerSlug, quantity?, currency?, promotionCode?, successUrl, cancelUrl, metadata? } | { kind, ... }: checkout, added or payment_required | Buy an add-on. Never retried. See Add-ons |
cancel(workspaceId, grantId) | string, string | { removeAt, message } | Remove a recurring add-on; it counts until the paid period ends |
grants(workspaceId) | string | IEntitlementGrant[] | What the workspace holds beyond its plan, for display |
Note
bb.addOns: Requires @buildbase/sdk 1.0.0 or later.
bb.usage
| Method | Parameters | Returns | Description |
|---|---|---|---|
record(workspaceId, options) | string, { quotaSlug, quantity, idempotencyKey? } | { used, consumed, included, available, overage, billedAsync } | Record usage against a quota |
recordBatch(workspaceId, options) | string, { items: Array<{ quotaSlug, quantity, idempotencyKey? }> } (max 100) | { success, total, succeeded, failed, results } | Record multiple quota events at once |
getQuota(workspaceId, slug) | string, string | { quotaSlug, consumed, included, available, overage, allowOverage } | Get current usage for one quota |
getAll(workspaceId) | string | { quotas } - status keyed by quota slug | Get all quota usage |
bb.workspace
| Method | Parameters | Returns | Description |
|---|---|---|---|
list() | - | Workspace[] | All workspaces for the current user |
get(workspaceId) | string | Workspace | Get workspace by ID |
create(options) | { name, image? } | Workspace | Create a new workspace |
update(workspaceId, options) | string, { name?, image? } | Workspace | Update workspace details (accepts partial fields) |
delete(workspaceId) | string | { success } | Delete a workspace |
bb.users
| Method | Parameters | Returns | Description |
|---|---|---|---|
list(workspaceId) | string | WorkspaceUser[] | List workspace members |
invite(workspaceId, email, role) | string, string, string | { userId, workspace, message } | Invite a user by email |
remove(workspaceId, userId) | string, string | { userId, workspace, message } | Remove a member |
updateRole(workspaceId, userId, role) | string, string, string | { userId, workspace, message } | Change a member's role |
bb.notification
| Method | Parameters | Returns | Description |
|---|---|---|---|
send(workspaceId, event, userId?, data?) | string, string, string?, object? | { sent, channels, notifiedCount?, reason? } | Send email + push notification for an event. Omit userId to notify all members |
bb.permissions
Both methods take an explicit userId - check any workspace member, not only the session's user.
| Method | Parameters | Returns | Description |
|---|---|---|---|
check(workspaceId, userId, permission) | string, string, string | string[] | boolean | Check if a user has a permission (an array requires all of them) |
resolve(workspaceId, userId) | string, string | Set<string> | Get all resolved permissions for a user |
bb.enterprise
Enterprise single sign-on for a workspace, as its admins see it. All run with the member's session, so the server's permission checks apply. bb.enterprise arrives in SDK 1.0.0.
| Method | Returns | Description |
|---|---|---|
status(workspaceId) | IEnterpriseStatus | The enterprise bound to the workspace, or { available: false }, with its SAML certificate warning (certificate). Needs workspace:settings:view |
createSetupLink(workspaceId, options?) | { url, expiresAt } | A five-minute setup link for the IT admin; options.intent is 'sso' (default), 'dsync', 'certificate_renewal', 'domain_verification' or 'audit_logs' (the audit log viewer, with company audit logs on). 'log_streams' is the console's alone (403 app_team_only). { purpose: 'roles' } opens the portal where the IT admin assigns roles: the directory's setup when one is linked, single sign-on's otherwise. Needs the company role the intent's area takes |
audit(workspaceId, query?) | { entries, nextCursor } | The company's audit trail, newest first; query takes actions, from, to, limit and cursor. Needs workspace:settings:edit |
exportAudit(workspaceId, query?) | string | The same filter as CSV, at most 50,000 rows, formula-guarded. Needs workspace:settings:edit |
createAuditExport(workspaceId, input?) | IEnterpriseAuditExport | Ask WorkOS for an export, with company audit logs on: from, to (at most 31 days, from the last three months or as long as WorkOS keeps the log, if less) and actions. Answers state: 'pending' |
auditExport(workspaceId, exportId) | IEnterpriseAuditExport | Read it until state is 'ready', with a url that works for ten minutes, or 'error' |
policy(workspaceId) | IEnterprisePolicy | The company's access policy: session length, IP allowlist, break-glass people, appTeamSessions, signInMethods (the ways its people may sign in without single sign-on, with what the app offers, who holds a passkey and the sessions outside the list), and networkRestriction, the header the company's proxy adds and what this request carried. Needs workspace:settings:edit |
workspacePolicies(workspaceId) | IEnterpriseWorkspacePoliciesView | null | Every workspace's stricter rules, with what each is warned about, and the company's bound workspaces to choose from; null on a server before them |
workspacePolicy(workspaceId, targetId) | IEnterpriseWorkspacePolicyView | null | One workspace's rules; null when it has none or is not one of the company's |
setWorkspacePolicy(workspaceId, targetId, input) | IEnterpriseWorkspacePolicySaved | Holds targetId to stricter rules, replaced whole, never looser than the company's (422 workspace_policy_not_stricter with fields), answering them with affected. Needs Access policy at Can manage and a recent confirmation |
removeWorkspacePolicy(workspaceId, targetId) | void | Back to the company's policy. Needs Access policy at Can manage and a recent confirmation |
savePolicy(workspaceId, input) | IEnterprisePolicy | Change it; only the fields given. signInMethods: { allowed } sets the list and null clears it. Refused with would_lock_you_out when the allowlist leaves out the server's own address, or the list leaves out the way the member signed in while they have no passkey; sign_in_method_not_offered for a way the app does not offer |
people(workspaceId, search?) | IEnterprisePerson[] | The company's people, searched by email or name, at most 50 |
signOut(workspaceId, scope) | { people, sessions } | { userId } or { everyone: true }: every session and connected app, now. { outsideMethods: true } ends the sessions that began a way the sign-in methods do not allow |
personSessions(workspaceId, userId) | IEnterprisePersonSession[] | One of the company's people's live sessions, newest first: device, browser and system, address and place, when it began, was last active and ends, method and issuedBy. Needs People at Can view; anyone not the company's is 404 not_a_person |
endPersonSession(workspaceId, userId, sessionRef) | { ended: number } | End that one session; the person's other sessions and connected apps stay. Needs People at Can manage; a ref that is not one of their live sessions is 404 session_not_found |
resetPasskeys(workspaceId, userId) | { removed, sessions } | Remove one of the company's people's passkeys for the app and sign them out, so their next sign-in sets up a new one. Needs People at Can manage and a recent sign-in; anyone not the company's is 404 not_a_person |
logStreams(workspaceId) | { streams, companyManages } | The company's log streams to its SIEM, each with its delivery state, never a secret |
createLogStream(workspaceId, input) | { stream, signingSecret? } | https, datadog or splunk; an HTTPS stream's signing secret comes back once. A refusal carries code and field |
updateLogStream(workspaceId, id, input) | { stream } | Change one; { enabled: false } pauses it |
rotateLogStreamSecret(workspaceId, id) | { stream, signingSecret } | A new signing secret for an HTTPS stream, answered once |
testLogStream(workspaceId, id) | { ok, status, ms } | Post one test event and answer what the receiver said |
deleteLogStream(workspaceId, id) | void | Stop sending at once |
logStream(workspaceId) | IEnterpriseWorkOSLogStreamView | The company's WorkOS log stream, or null, and how long WorkOS keeps its log, with company audit logs on; read only |
insights(workspaceId, days?) | IEnterpriseInsights | People, sign-ins, refusals by reason and a day-by-day series over 7, 30 (default) or 90 days |
admins(workspaceId) | IEnterpriseAdminsView | The company's admins, with who named them (console, app or mapping) |
addAdmin(workspaceId, userId) | IEnterpriseAdminsView | Name one of the company's people a company admin; from then on only the named admins manage the company |
removeAdmin(workspaceId, userId) | IEnterpriseAdminsView | Remove one; one the identity provider made is refused with managed_by_idp |
connectedApps(workspaceId) | IEnterpriseConnectedApp[] | The apps and agents the company's people connected, with how many people and whether the policy allows each |
connectedAppGrants(workspaceId, client) | IEnterpriseConnectedAppGrant[] | One app's people and the scopes each granted |
revokeConnectedApp(workspaceId, input) | { people } | { clientId } for everyone at the company, or { clientId, userId } for one person: the grant and its tokens end now |
updateRole(workspaceId, roleId, input) | IEnterpriseCompanyRole | Change one of the company's roles. assignableInWorkOS: true publishes it to WorkOS for the company's IT admin to assign, and false takes it out; Company admin is refused with company_admin_console_only, and one still assigned in WorkOS with role_in_use |
updateGroup(workspaceId, groupId, input) | IEnterpriseGroupSaved | Change a group; assignableInWorkOS publishes it or takes it out the same way |
workosRoles(workspaceId) | IEnterpriseWorkOSRolesView | The company's roles in WorkOS: whether they are in sync, what is published, the slugs its people carry, and the issues. Needs Company roles at Can view |
refreshWorkOSRoles(workspaceId) | IEnterpriseWorkOSRolesView | Read the company's roles from WorkOS now, and with a directory linked, queue a read of the whole directory, which reads everyone's roles again. Needs Setup at Can manage |
The setup link is a credential: redirect a browser to it, and never log or store it.
A change to the company's security settings (the policy, signing everyone out, setup links, company admins and roles, groups that carry a role, new keys and service accounts, log streams, passkey resets) needs the member to have signed in or confirmed in the last 10 minutes. Otherwise it throws an error with status 403 and code: 'reauth_required', and the session is kept: send the member to confirm in their browser with requireReverification, then call again (confirming it's you). A session from the token exchange never counts as recent, so it gets reverifiable: false.
Next Steps
- Commerce from your server - Items, orders, refunds and the rest of selling, with an org API key.
- Webhooks - Handle events in your backend.
- Quotas - Usage recording and metering.