Skip to Content
Features

Also in the box

Beyond typed RPC and the AI/MCP story, every procedure definition gives you:

REST + OpenAPI 3.1

A procedure with a method and path (route.get('/notes')) is a REST endpoint; toOpenApiDocument(appRouter, { info }) emits an OpenAPI 3.1 spec (file uploads are documented as multipart/form-data). Same validation, same handler.

.get() also marks a procedure as a read: only reads answer GET (and so can sit behind a link or <img src>). The path is optional — route.get() is an RPC-only read.

Streaming & real-time

route.stream(async function* () { … }) — streaming is just an async generator, delivered as NDJSON over HTTP, or as Server-Sent Events with createClient(url, { streamFormat: "sse" }) when a proxy buffers NDJSON. Pair it with a pub/sub (createInMemoryPubSub, createRedisPubSub, or createPgPubSub on Postgres LISTEN/NOTIFY) for live subscriptions. On the client, for await (…) over the same typed method.

watch: route.stream(async function* ({ ctx, signal }) { // `signal` aborts when the client disconnects, cancels or unsubscribes for await (const ev of ctx.pubsub.subscribe("notes", { signal })) yield ev }) const ac = new AbortController() for await (const ev of api.watch(undefined, { signal: ac.signal })) { /* … */ }

WebSocket transport

The same procedures run over one WebSocket: calls and subscriptions multiplexed.

Server. attachWsServer(wss, router, opts) takes your ws server and accepts upgrades on one path. It requires an Origin allowlist and builds the context once per connection, both before the socket opens, and sets limits: 1 MB messages, 1 MB of unsent data, 100 subscriptions per connection, a 30 s heartbeat. revalidate re-checks long-lived sessions, closeWhere signs people out, and close() shuts down cleanly.

const wss = new WebSocketServer({ noServer: true, maxPayload: 1_000_000 }) const live = attachWsServer(wss, appRouter, { path: '/ws', allowedOrigins: ['https://app.example.com'], createContext: async (req) => ({ user: await getSession(req.headers) }), }) server.on('upgrade', (req, socket, head) => live.handleUpgrade(req, socket, head))

Browser. createWsConnection(url) reconnects on its own with backoff, retries when the browser comes back online, and resubscribes open subscriptions, so a for await loop survives a dropped connection:

const conn = createWsConnection<AppRouter>(`wss://${location.host}/ws`) conn.onStatus((s) => setBanner(s)) // connecting | connected | reconnecting | stopped | closed for await (const ev of conn.api.notes.watch()) render(ev)

Next.js can’t accept WebSocket upgrades itself; the README has a recipe for a small Node server in front of Next.

Background jobs

Long work (an AI call, an export) runs off the request and survives a deploy:

const jobs = createJobs({ store: createPgJobStore(pool), pubsub, context: () => ({ db }) }) const summarize = jobs.define('summarize', { input: s.object({ docId: s.string() }), run, retries: 3 }) start: authed.input(s.object({ docId: s.string() })).background(summarize) // → { jobId } watch: authed.input(s.object({ jobId: s.string() })) // check the job is theirs: see the README .stream(({ input, signal }) => summarize.watch(input.jobId, { signal }))

Retries with backoff, one running job per key, a concurrency cap per job name, and status streamed over the pub/sub. Stores: in-memory and Postgres. In the browser, useJob (from dendra/react) or followJob follows a job to completion, reconnecting as needed, with no polling.

In-process caller

In a Server Component, skip HTTP entirely: createCaller(appRouter, ctx) runs the procedure in-process with no round-trip and no serialization — so a Date stays a Date. Over HTTP or WebSocket, client results are typed as what survives JSON (Jsonify<T>): the same Date is typed string.

dendra/next turns errors into pages in a Server Component:

import { orPage } from 'dendra/next' // NOT_FOUND / BAD_REQUEST → notFound(); UNAUTHORIZED → redirect('/sign-in') const note = await orPage(caller.notes.get({ id }), { signIn: '/sign-in' })

Middleware & auth

dendra never authenticates — you guard procedures with .use():

const authed = route.use(({ ctx }) => { if (!ctx.user) throw new DendraError('UNAUTHORIZED', 'Sign in') return { user: ctx.user } // refines ctx for downstream handlers })

A tool behind .use(auth) is auth-guarded for the model too.

After-hooks (audit, usage, metrics)

.after() runs once a call settles — success or failure — on every transport, including AI/MCP tool calls. It’s awaited, and a hook that throws is only logged:

const audited = authed.after(({ ctx, path, transport, ok, code, durationMs }) => ctx.db.audit.insert({ user: ctx.user.id, path, transport, ok, code, durationMs }), )

A hook only sees calls that passed the .use()s before it — put it before the auth guard to also record rejections.

Files in and out

Uploads and downloads are ordinary procedures, so .use() and .after() cover them:

upload: tenant .input(s.object({ workspaceId: s.integer(), image: s.file({ types: ['image/png', 'image/webp'], maxBytes: 8_000_000 }) })) .handler(({ input }) => store(input.image)), // input.image: File cover: tenant .get() // reads answer GET → usable in <img> .input(s.object({ id: s.integer() })) .handler(() => file(bytes, { type: 'image/webp', inline: true })),

On the client, api.upload({ …, image }) sends multipart, a file() result arrives as a Blob, and urlFor(api.cover, { id }) gives an <img src>. File types are checked from the bytes, bodies are capped (10 MB default), file responses send nosniff, and HTML/SVG never render inline.

Audit hooks see { file: { type, filename, size } } for a file result, never the bytes. A procedure with file input can’t be .ai() — models can’t send files.

Security: CSRF by default

dendra’s client sends X-Dendra: 1 on every request, and the server only accepts what a cross-site page can’t forge without a CORS preflight:

RequestAllowed whenOtherwise
GET / HEADthe procedure is a .get() read405
PUT / PATCH / DELETE (RPC)never405
POST, JSONContent-Type: application/json415
POST, multipartX-Dendra: 1 header403
POST, plain HTML formallowFormPosts: true (then CSRF is your job)415

File responses always send X-Content-Type-Options: nosniff, sanitize the filename, and never render HTML/SVG/XML inline unless you set allowUnsafeInline.

WebSockets bypass CORS: any site can open one with the user’s cookies. attachWsServer refuses a foreign or missing Origin with 403 before the socket opens. The low-level attachWs/connectWs/createWsSession/createWsClient are for runtimes without the ws package, and have no Origin check, limits or reconnect: with them, those are yours.

Class controllers (NestJS-style, no decorators)

A class whose fields are procedures; put an instance in the router. Keep injected deps in #private fields:

class UsersController { constructor(#db) {} list = route.handler(({ ctx }) => this.#db.users.all()) create = route.input(s.object({ name: s.string() })).handler(/* … */) } const appRouter = { users: new UsersController(db) /* … */ }

Request batching

The typed client can batch concurrent unary calls into one HTTP request — transparent to your code. createClient(url, { batch: true }) sends same-tick calls to __batch?p=a,b (so logs and network mocks still see procedure names), and each result streams back as soon as it settles — a slow call never holds up a quick one. Pass { batch: false } to send a call on its own.

Agent helpers

Opt-in peer-dep subpaths: dendra/anthropic (runAgent — the model↔tool loop), dendra/react (useAssistant — the chat thread + streaming), dendra/memory (persistent recall), and dendra/next (orPage — errors as Next pages). Use them, or bring your own loop/UI — the core tool-shaping primitives are enough on their own. runAgent, useAssistant and the context layer are experimental: they may change in a minor release.

Standard Schema

Validate with the built-in s.* (including s.file()), or any Standard Schema library — Zod 3 and 4, Valibot, or ArkType — interchangeably. Each is type-checked in dendra’s test suite, so input infers correctly. Their JSON Schema reaches OpenAPI and AI tools too: Zod 4 and ArkType publish it, and a Valibot schema does once wrapped in toStandardJsonSchema. An .ai() tool refuses an input without one, so the model always sees its parameters.

Last updated on