SDK Reference
One import, zero config. AI, storage, email, and auth — all authenticated by a single BROKR_TOKEN that Brokr injects automatically.
Overview & Setup
The Brokr SDK is a drop-in client for apps provisioned by Brokr. Zero config — it reads BROKR_TOKEN from the environment, which Brokr injects automatically at deploy time.
npm install @brokr/sdk
// lib/brokr.ts — create this onceimport { createBrokr } from '@brokr/sdk';export const brokr = createBrokr();// Then use anywhere:const reply = await brokr.ai.chat([{ role: 'user', content: 'Hello' }]);const { key } = await brokr.storage.upload(file, 'avatar.png', 'image/png');await brokr.email.send({ to: 'user@example.com', subject: 'Hi', html: '<p>Hey</p>' });
createBrokr() accepts optional overrides for testing:
const brokr = createBrokr({token: 'custom-token', // override BROKR_TOKENgatewayUrl: 'http://localhost:8787', // override gateway URL});
Available in TypeScript, Python, and Go. TypeScript is on npm — Python and Go packages are written and pending publish.
Runtime Client
createBrokr() returns a BrokrRuntime instance with three sub-clients:
| Client | Access | Purpose |
|---|---|---|
BrokrAIClient | brokr.ai | Chat completions, streaming, OpenAI SDK compatibility. |
BrokrStorageClient | brokr.storage | Upload files, get presigned URLs, browser-direct uploads. |
BrokrEmailClient | brokr.email | Send transactional email via Resend. |
BrokrAuthClient | brokr.auth | User auth (lazily initialized — only loaded when accessed). |
All clients authenticate via BROKR_TOKEN. Every request routes through api.brokr.sh — the gateway resolves per-stack provider credentials server-side.
AI
brokr.ai.chat() sends a chat completion request to the Brokr AI gateway. The gateway is OpenAI-compatible — you can also use the official openai SDK.
// Non-streamingconst reply = await brokr.ai.chat([{ role: 'user', content: 'Summarize this contract in 3 bullet points.' },]);console.log(reply.content);console.log(reply.usage); // { promptTokens, completionTokens }// With optionsconst reply = await brokr.ai.chat(messages, {model: 'claude-sonnet-4-20250514',maxTokens: 1000,temperature: 0.7,});
brokr.ai.stream() returns an async generator that yields text strings directly:
for await (const text of brokr.ai.stream(messages)) {process.stdout.write(text);}
OpenAI SDK compatibility — use brokr.ai.baseURL and brokr.ai.apiKey to route the official OpenAI SDK through Brokr:
import OpenAI from 'openai';const ai = new OpenAI({baseURL: brokr.ai.baseURL, // https://api.brokr.sh/v1apiKey: brokr.ai.apiKey, // your BROKR_TOKEN});const res = await ai.chat.completions.create({model: 'gpt-4o',messages: [{ role: 'user', content: 'Hello' }],});
Model aliases for common use cases:
| Alias | Model | Use case |
|---|---|---|
models.FAST | deepseek-chat | Cheapest and fastest. |
models.SMART | claude-sonnet-4-20250514 | Most capable. |
models.BALANCED | deepseek-chat | Default for most tasks. |
The gateway supports Claude, GPT, Deepseek, and more. Pass any model name — the gateway routes to the right provider.
Storage
brokr.storage.upload() uploads data to R2 and returns a stable key. brokr.storage.url() generates presigned download URLs. brokr.storage.getUploadUrl() returns a presigned upload URL for browser-direct uploads.
// Server-side upload — one callconst { key } = await brokr.storage.upload(fileBuffer, // Buffer | Uint8Array | string | Blob'invoice.pdf','application/pdf',);// Get a download URL (presigned, ~15 min default)const { url } = await brokr.storage.url(key);const { url: longUrl } = await brokr.storage.url(key, { expiresIn: 3600 });// Browser-direct upload (large files, no server proxy)const { url, key } = await brokr.storage.getUploadUrl('resume.pdf', 'application/pdf');await fetch(url, { method: 'PUT', body: file });
Store the key in your database. Presigned download URLs expire — generate them on demand, never store them.
brokr.email.send() sends transactional email via Resend. The from address defaults to noreply@{your stack domain}. Provider credentials are resolved server-side — you never touch them.
await brokr.email.send({to: 'user@example.com',subject: 'Welcome!',html: '<h1>Welcome to the app</h1>',});// Multi-recipient + plain-text fallbackawait brokr.email.send({to: ['alice@example.com', 'bob@example.com'],subject: 'Your weekly digest',html: '<h1>This week</h1><p>Summary...</p>',text: 'This week\nSummary...',});// Custom from address (must be on your verified domain)await brokr.email.send({to: user.email,from: 'orders@smooth.app',subject: 'Order confirmed',html: `<p>Order #${order.id} shipped.</p>`,});
Auth
brokr.auth provides server-side authentication utilities for stacks provisioned with the auth capability. The auth client is lazily initialized — it only loads when you access it.
// Get the current user from a requestconst user = await brokr.auth.currentUser(request);// Get session infoconst session = await brokr.auth.getSession(request);
The auth capability uses Brokr Auth under the hood. When you add it to a stack with brokr add auth, Brokr auto-scaffolds the auth files and installs dependencies.
Management Client
createBrokrClient() is for tools that manage stacks — the CLI uses this internally. It connects to the Brokr tRPC API, not the gateway.
import { createBrokrClient } from '@brokr/sdk';const client = createBrokrClient({apiUrl: 'https://brokr.sh',accessToken: token,});// Stack CRUDconst stacks = await client.listStacks();const stack = await client.getStack('my-app');await client.deleteStack('my-app');// Add a capabilityawait client.add('my-app', 'database');
Most users will never need the management client — it's for building integrations and tooling on top of Brokr. Use createBrokr() for app code.
Error Classes
All SDK errors extend BrokrError. Catch specific classes to handle different failure modes.
| Class | When | Properties |
|---|---|---|
BrokrError | Base class for all errors. | code, capability, retryable |
BrokrAuthError | BROKR_TOKEN missing or invalid. | code: BROKR_TOKEN_MISSING | BROKR_TOKEN_INVALID |
BrokrRateLimitError | HTTP 429 from the gateway. | retryAfter (seconds), retryable: true |
BrokrNetworkError | Gateway unreachable. | retryable: true |
import { BrokrAuthError, BrokrRateLimitError } from '@brokr/sdk';try {const reply = await brokr.ai.chat(messages);} catch (err) {if (err instanceof BrokrAuthError) {console.error('Token issue:', err.code);} else if (err instanceof BrokrRateLimitError) {console.log(`Rate limited. Retry after ${err.retryAfter}s`);}}
TypeScript Types
All types are exported from @brokr/sdk for use in your app.
import type {ChatMessage, // { role: 'user' | 'assistant' | 'system'; content: string }ChatOptions, // { model?: string; maxTokens?: number; temperature?: number }ChatResponse, // { content: string; model: string; usage: { promptTokens, completionTokens } }UploadResult, // { key: string }EmailParams, // { to: string | string[]; subject: string; html?: string; text?: string; from?: string }RuntimeOptions, // { token?: string; gatewayUrl?: string }BrokrRuntime, // Main client classBrokrAIClient,BrokrStorageClient,BrokrEmailClient,BrokrError,BrokrAuthError,BrokrRateLimitError,BrokrNetworkError,} from '@brokr/sdk';