SDK Reference
TypeScript
Zero config

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.

bash
npm install @brokr/sdk
bash
// lib/brokr.ts — create this once
import { 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:

bash
const brokr = createBrokr({
token: 'custom-token', // override BROKR_TOKEN
gatewayUrl: '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:

ClientAccessPurpose
BrokrAIClientbrokr.aiChat completions, streaming, OpenAI SDK compatibility.
BrokrStorageClientbrokr.storageUpload files, get presigned URLs, browser-direct uploads.
BrokrEmailClientbrokr.emailSend transactional email via Resend.
BrokrAuthClientbrokr.authUser 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.

bash
// Non-streaming
const 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 options
const 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:

bash
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:

bash
import OpenAI from 'openai';
const ai = new OpenAI({
baseURL: brokr.ai.baseURL, // https://api.brokr.sh/v1
apiKey: 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:

AliasModelUse case
models.FASTdeepseek-chatCheapest and fastest.
models.SMARTclaude-sonnet-4-20250514Most capable.
models.BALANCEDdeepseek-chatDefault 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.

bash
// Server-side upload — one call
const { 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.

Email

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.

bash
await brokr.email.send({
to: 'user@example.com',
subject: 'Welcome!',
html: '<h1>Welcome to the app</h1>',
});
// Multi-recipient + plain-text fallback
await 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.

bash
// Get the current user from a request
const user = await brokr.auth.currentUser(request);
// Get session info
const 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.

bash
import { createBrokrClient } from '@brokr/sdk';
const client = createBrokrClient({
apiUrl: 'https://brokr.sh',
accessToken: token,
});
// Stack CRUD
const stacks = await client.listStacks();
const stack = await client.getStack('my-app');
await client.deleteStack('my-app');
// Add a capability
await 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.

ClassWhenProperties
BrokrErrorBase class for all errors.code, capability, retryable
BrokrAuthErrorBROKR_TOKEN missing or invalid.code: BROKR_TOKEN_MISSING | BROKR_TOKEN_INVALID
BrokrRateLimitErrorHTTP 429 from the gateway.retryAfter (seconds), retryable: true
BrokrNetworkErrorGateway unreachable.retryable: true
bash
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.

bash
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 class
BrokrAIClient,
BrokrStorageClient,
BrokrEmailClient,
BrokrError,
BrokrAuthError,
BrokrRateLimitError,
BrokrNetworkError,
} from '@brokr/sdk';