Skip to content

Typed APIs

sygnal/api builds a typed client from an API contract that your server already has. With a client, you don’t write a URL, a route or a reply type in a component. Each procedure of the contract becomes a function that builds a request: the same plain data the HTTP and socket drivers already take. Effects stay data, replies still come back as actions, and the drivers’ features (resources, the query cache, latest, retries, reconnects) all apply.

The procedureThe call returnsUse it in
a GETa request tagged with the endpointresources, or an HTTP sink
any other methoda request with a JSON bodyan HTTP sink, with ok / error reply actions
a stream (an oRPC event iterator, or .sse(path))a server-sent events connectionconnections

There are three adapters, one per kind of contract. All of them use plain JSON on the wire:

  • orpcClient(contract): an oRPC contract router, served by oRPC’s OpenAPIHandler. This is the recommended pairing.
  • openApiClient<paths>(): the paths type that openapi-typescript generates from any OpenAPI document, for any back end.
  • honoClient<ExtractSchema<typeof app>>(): the routes of a Hono app.

Sygnal doesn’t ship a server. It is a client for the server you choose. (For Telefunc’s server functions under Vike, see Server Functions.)

Contract-first is the primary form. The contract is a module of its own: the API’s definition, reviewed and versioned as one, and shared by the client and the server. For an app whose API serves only itself, there is also a function-first form: you write the server functions in *.server.ts files, and their exports are the contract. Both forms build the same requests and use the same oRPC server.

The contract is the one module the client and the server share. In this demo, a stand-in server answers the way oRPC’s OpenAPIHandler does: plain JSON, a 400 with data.issues for invalid input, and a declared error by its code.

import { oc } from '@orpc/contract'
import { z } from 'zod'
const Quote = z.object({ id: z.number(), text: z.string() })
export const contract = {
quotes: {
list: oc.route({ method: 'GET', path: '/quotes' }).output(z.array(Quote)),
add: oc.route({ method: 'POST', path: '/quotes' })
.input(z.object({ text: z.string().min(3) }))
.output(Quote)
.errors({ DUPLICATE: { status: 409, data: z.object({ id: z.number() }) } }),
remove: oc.route({ method: 'DELETE', path: '/quotes/{id}' })
.input(z.object({ id: z.coerce.number() }))
.output(z.object({ removed: z.boolean() })),
},
}
Demo server
const quotes = [{ id: 1, text: 'Start where you are.' }]
let next = 2
export default {
'GET /api/quotes': () => ({ json: quotes, delayMs: 300 }),
'POST /api/quotes': ({ json }) => {
if (json.text.length < 3) return { status: 400, json: { defined: false, code: 'BAD_REQUEST', status: 400, message: 'Input validation failed', data: { issues: [{ path: ['text'], message: 'At least 3 characters' }] } } }
const dup = quotes.find((q) => q.text === json.text)
if (dup) return { status: 409, json: { defined: true, code: 'DUPLICATE', status: 409, message: 'DUPLICATE', data: { id: dup.id } } }
const quote = { id: next++, text: json.text }
quotes.push(quote)
return { json: quote, delayMs: 300 }
},
'DELETE /api/quotes/:id': ({ params }) => {
const i = quotes.findIndex((q) => q.id === Number(params.id))
if (i >= 0) quotes.splice(i, 1)
return { json: { removed: i >= 0 } }
},
}
Quotes.jsx
import { orpcClient } from 'sygnal/api'
import { contract } from './contract.js'
const api = orpcClient(contract, { prefix: '/api' })
function Quotes({ state }) {
return (
<div>
<form className="add">
<input className="draft" value={state.draft} aria-label="New quote" />
<button type="submit">Add</button>
</form>
<p className="message">{state.message}</p>
<ul>
{(state.quotes.data ?? []).map((q) => (
<li>{q.text} <button className="remove" data={{ id: q.id }} aria-label={`Remove ${q.text}`}>×</button></li>
))}
</ul>
</div>
)
}
Quotes.initialState = { draft: '', message: '', quotes: { status: 'idle' } }
Quotes.resources = {
quotes: () => api.quotes.list(),
}
Quotes.intent = ({ DOM }) => ({
TYPE: DOM.input('.draft').value(),
ADD: DOM.select('.add').events('submit', { preventDefault: true }),
REMOVE: DOM.click('.remove').data('id', Number),
})
Quotes.model = {
TYPE: (state, draft) => ({ ...state, draft }),
ADD: { HTTP: (state) => api.quotes.add({ text: state.draft }, { ok: 'ADDED', error: 'FAILED', invalidates: [api.quotes.list] }) },
ADDED: (state, quote) => ({ ...state, draft: '', message: `Added #${quote.id}` }),
FAILED: (state, { body }) => ({
...state,
message: body?.code === 'DUPLICATE' ? `Already there: #${body.data.id}` : body?.data?.issues?.[0]?.message ?? 'Could not add it',
}),
REMOVE: { HTTP: (state, id) => api.quotes.remove({ id }, { invalidates: [api.quotes.list] }) },
}

Add a quote, add it again, or add a short one. Each reply arrives as the action the call named.

  • api.quotes.list() is { url: '/api/quotes', endpoint: 'quotes.list', tags: ['api:quotes.list'] }. As a resource it is fetched when declared, and it refetches when the derived input changes.
  • api.quotes.add(input, options) is a POST with json: input. The options are the request’s own fields: ok, error, key, latest, timeoutMs, retry and the rest of the request fields.
  • invalidates: [api.quotes.list] refetches the resources built by that endpoint after a 2xx reply, using its api:quotes.list tag. A tag string works too.
  • Path parameters (/quotes/{id}, /files/{+path}) are filled from the input and removed from it. For a GET, the rest of the input goes in the query string in oRPC’s bracket notation (tags[0]=a, filter[min]=2). For other methods, it is the JSON body.
  • Each request carries endpoint, the procedure’s id. It is an app key, so it isn’t sent, and devtools and t.requests show it.

An oRPC event iterator is read as server-sent events. Give the procedure .route({ method: 'GET' }), then declare the call in connections. Each event arrives as the message action:

contract.js
import { oc, eventIterator } from '@orpc/contract'
export const contract = {
quotes: {
// …
feed: oc.route({ method: 'GET', path: '/quotes/feed' })
.input(z.object({ tag: z.string().optional() }))
.output(eventIterator(Quote)),
},
}
Quotes.jsx
Quotes.connections = (state) => ({
feed: api.quotes.feed({ tag: state.tag }, { message: 'ARRIVED', resume: true }),
})
Quotes.model = {
ARRIVED: (state, quote) => ({ ...state, live: [quote, ...state.live] }),
}

The connection takes every option of an SSE connection: open, close, error, resume, staleAfterMs, reconnect. A changed input closes the old stream and opens the new one. The procedure on the server is an async generator, and one yield is one event.

TypeScript infers every input, reply and error from the contract. The canonical component form names the reply actions’ data with Output and ApiFailure:

Quotes.tsx
import type { Component, Resource, FetchRequest, FetchSource, ActionsOf, IntentSources } from 'sygnal'
import type { Output, ApiFailure } from 'sygnal/api'
import { api } from './api'
type State = { draft: string; message: string; quotes: Resource<Output<typeof api.quotes.list>> }
type Drivers = { HTTP: { source: FetchSource; sink: FetchRequest } }
const intent = ({ DOM }: IntentSources<State, Drivers>) => ({ TYPE: DOM.input('.draft').value(), ADD: DOM.click('.add') })
type Actions = ActionsOf<typeof intent> & {
ADDED: Output<typeof api.quotes.add>
FAILED: ApiFailure<typeof api.quotes.add>
}
export const Quotes: Component<State, {}, Drivers, Actions> = ({ state }) => <ul>…</ul>
Quotes.model = {
ADD: { HTTP: (state) => api.quotes.add({ text: state.draft }, { ok: 'ADDED', error: 'FAILED' }) },
ADDED: (state, quote) => ({ ...state, message: `Added #${quote.id}` }), // quote: { id: number; text: string }
FAILED: (state, { body }) => ({
...state,
message: body?.defined && body.code === 'DUPLICATE' ? `#${body.data.id}` : body?.message ?? 'Failed', // narrowed by code
}),
}
  • The input is checked at the call: a missing field, a wrong type or an unknown procedure is a compile error.
  • Output<typeof endpoint> is the reply as JSON delivers it (Jsonify). A z.date() the server returns is a string here, because that is what arrives.
  • ApiFailure<typeof endpoint> is the error action’s data with a typed body. With oRPC, the body is the union of the procedure’s declared errors (by code, with their typed data) and { defined: false, … } for anything else, including input validation (data.issues).
  • The server implements the same contract with implement(contract), so a handler that returns the wrong shape is a compile error on the server too.

In JavaScript, sygnal-check reports a misspelled procedure (SYG691): it follows api to its orpcClient(contract) call, and the contract to its object literal, through imports.

On the server, implement the contract with oRPC and serve it with the OpenAPIHandler. It is a Fetch handler (Request → Response), so it mounts in Hono, a Worker or Node. In development, sygnal({ api: { handler: 'server/api.ts' } }) serves a module’s default export (a Fetch handler) at /api from Vite’s dev server:

server.ts
import { implement } from '@orpc/server'
import { OpenAPIHandler } from '@orpc/openapi/fetch'
import { contract } from './contract'
const os = implement(contract)
const router = os.router({
quotes: {
list: os.quotes.list.handler(() => db.quotes.all()),
add: os.quotes.add.handler(({ input, errors }) => {
const dup = db.quotes.byText(input.text)
if (dup) throw errors.DUPLICATE({ data: { id: dup.id } })
return db.quotes.insert(input)
}),
// …
},
})
const handler = new OpenAPIHandler(router)
export async function handle(request: Request) {
const { matched, response } = await handler.handle(request, { prefix: '/api' })
return matched ? response : new Response('Not found', { status: 404 })
}
  • Use the OpenAPIHandler, not the RPCHandler. The RPC protocol wraps every value in { json, meta } to carry rich types. A Sygnal request is plain JSON both ways, and the network-calls research rules out rich serialisation on the wire.
  • GET input comes from the query string, so every value arrives as a string. Give non-string fields of a GET procedure a coercing schema: z.coerce.number(), z.coerce.boolean().
  • An input with inputStructure: 'detailed' (separate params, query, headers and body) isn’t supported yet. orpcClient throws when it creates the client.

The typed-api example is a complete app: the contract, the oRPC server in Vite’s dev server, a component with a resource, a mutation, a delete, a live feed and one function-first call, and its tests (one of them builds the client and searches it for server code).

A request is data, so renderComponent fakes answer it like any other request. An endpoint can be the target of t.respond, t.fail and t.push. fixture(endpoint, data) checks the data against the contract’s output schema, so a fixture that drifts from the contract fails the test:

Quotes.test.jsx
import { renderComponent } from 'sygnal'
import { fixture, errorFixture } from 'sygnal/api'
import { api } from './api'
import { Quotes } from './Quotes'
it('adds a quote, and shows a duplicate', async () => {
const t = renderComponent(Quotes)
await t.ready()
await t.respond('HTTP', fixture(api.quotes.list, [{ id: 1, text: 'Start where you are.' }]), api.quotes.list)
await t.simulateEvent('.draft', 'input', { value: 'Less, but better.' })
await t.simulateEvent('.add', 'submit')
expect(t.requests('HTTP').at(-1)).toMatchObject({ url: '/api/quotes', method: 'POST', json: { text: 'Less, but better.' } })
await t.respond('HTTP', fixture(api.quotes.add, { id: 2, text: 'Less, but better.' }), api.quotes.add)
expect(t.state.message).toBe('Added #2')
const dup = errorFixture(api.quotes.add, 'DUPLICATE', { id: 2 }) // { status: 409, body: { defined: true, code, … } }
await t.simulateEvent('.add', 'submit')
await t.fail('HTTP', dup.status, { request: api.quotes.add, body: dup.body })
})
  • fixture(endpoint, data) takes the server’s value (a Date stays a Date) and returns it the way JSON delivers it. A stream endpoint’s fixture is one event: t.push('WS', fixture(api.quotes.feed, quote), api.quotes.feed).
  • errorFixture(endpoint, code, data, message?) builds a declared error, and checks its data against the error’s schema.
  • The real server, in-process: a Fetch handler can be the drivers’ fetch, with no port and no mocks. The test then runs the real procedures:
Quotes.server.test.js
const fetch = (url, init) => handle(new Request(new URL(url, 'http://localhost'), init))
const t = renderComponent(Quotes, { drivers: { HTTP: makeFetchDriver({ fetch }), WS: makeSocketDriver({ fetch }) } })

A stream connection with headers is read over fetch (in Node too), so in-process tests can include streams: pass the client a headers option, such as the contract hash below.

After a deploy, a tab that was loaded earlier still runs the old client against the new server. Send a hash of the contract with every request, check it on the server, and the stale tab learns it must reload instead of sending requests the new API may reject:

api.ts
import { orpcClient, contractHash } from 'sygnal/api'
import { contract } from './contract'
export const api = orpcClient(contract, { prefix: '/api', headers: { 'x-api-contract': contractHash(contract) } })
server.ts
import { contractHash, contractSkew } from 'sygnal/api'
const hash = contractHash(contract)
export async function handle(request: Request) {
const skew = contractSkew(request, { hash, header: 'x-api-contract' })
if (skew) return skew // 409 CONTRACT_SKEW, in oRPC's error shape
// … the OpenAPIHandler
}
App.jsx
import { makeFetchDriver, makeSocketDriver } from 'sygnal'
import { contractFetch } from 'sygnal/api'
const fetch = contractFetch({ onSkew: () => showReloadBanner() })
App.drivers = { HTTP: makeFetchDriver({ fetch }), WS: makeSocketDriver({ fetch }) }
  • contractHash(contract) hashes the procedures’ ids, routes, input and output JSON Schemas (from the schemas’ Standard JSON Schema support; zod 4 has it) and error codes. Any other value, such as an OpenAPI document, is hashed as its stable JSON. The hash is for detecting change only; it isn’t cryptographic.
  • contractSkew(request, { hash, header }) answers a request that sends another hash with a 409 CONTRACT_SKEW. A request without the header passes, unless you set require: true.
  • isContractSkew(failure) tells an error action or a failed resource apart. contractFetch() reports SYG690 once and calls onSkew for each skew answer.

orpcClient needs the contract’s routes, not its schemas, unless it validates replies on the client (validate: true). Name the contract module in the Vite plugin, and client code gets only what the client uses: each procedure’s route, kind and declared error statuses, plus the contract hash computed at build time. The schema library is left out of the bundle:

vite.config.ts
import { defineConfig } from 'vite'
import sygnal from 'sygnal/vite'
export default defineConfig({
plugins: [sygnal({ api: { contracts: ['src/contract.ts'], handler: 'server/api.ts' } })],
})

Nothing changes in the app: orpcClient(contract) and contractHash(contract) take the replaced module as they took the original. In the typed-api example, the client bundle goes from 226.8 kB to 135.3 kB (73.7 kB to 47.7 kB gzipped).

  • The module runs in Node at build time (and in the dev server) so the plugin can read its schemas. Keep a contract module free of side effects.
  • Only contracts are kept. Another export of the module (a schema) is left out, so a client import of it fails the build. Put a schema the client needs in a module of its own.
  • validate: true needs the schemas. orpcClient throws if the module was replaced, so leave that module out of contracts.
  • Tests run the module as written (under Vitest nothing is replaced), so fixture() still checks against the schemas.

For an API described by an OpenAPI document (Go, Python, Rails, or oRPC’s OpenAPIGenerator), generate its paths type with openapi-typescript (npx openapi-typescript openapi.json -o api-types.ts), then name each endpoint once:

api.ts
import { openApiClient } from 'sygnal/api'
import type { paths } from './api-types'
const http = openApiClient<paths>({ prefix: '/api' })
export const getQuote = http.get('/quotes/{id}')
export const listQuotes = http.get('/quotes')
export const addQuote = http.post('/quotes')
export const quoteFeed = http.sse<Quote>('/quotes/feed') // the event type is yours to name
getQuote({ params: { path: { id: 1 } } }, { ok: 'LOADED' }) // { url: '/api/quotes/1', … }
listQuotes({ params: { query: { tag: 'calm', tags: ['a', 'b'] } } })
addQuote({ body: { text: 'Less, but better.' } }, { ok: 'ADDED', error: 'FAILED', invalidates: [listQuotes] })

The input is openapi-fetch’s { params: { path, query, header }, body }. Query arrays repeat the key (tags=a&tags=b), and objects use key[field]. Output<typeof getQuote> is the 2xx JSON response, and ErrorBody<typeof getQuote> the other responses’ JSON. The adapter has no runtime schema, so fixture() is checked by the compiler only.

For a Hono app whose routes carry types (validators, c.json(value, status)), pass Hono’s own ExtractSchema:

api.ts
import { honoClient } from 'sygnal/api'
import type { ExtractSchema } from 'hono/types'
import type { app } from '../server/app'
const hono = honoClient<ExtractSchema<typeof app>>()
export const getQuote = hono.get('/api/quotes/:id')
export const addQuote = hono.post('/api/quotes')
getQuote({ param: { id: '1' } }, { ok: 'LOADED' })
addQuote({ json: { text: 'Less, but better.' } }, { ok: 'ADDED', error: 'FAILED' })

The input is hc’s { param, query, json, header }. Output is the output of the route’s 2xx responses, and ErrorBody that of the others. A streamSSE route is hono.sse<Event>('/api/feed').

When the API exists only for this app, you can skip the separate contract. Write each server function in a *.server.ts file and import it from components. The file’s path and its export names are the contract:

src/ideas.server.ts
import { z } from 'zod'
import { query, mutation } from 'sygnal/api'
import { db } from '../server/db'
export const suggest = query(z.object({ tag: z.string() }), async ({ tag }) => ({ text: await db.ideas.pick(tag) }))
export const save = mutation(
z.object({ text: z.string().min(3) }),
async ({ text }, { context, errors }) => {
if (await db.ideas.full()) throw errors.FULL()
return db.ideas.insert({ text, by: context.user })
},
{ errors: { FULL: { status: 507, message: 'No room for more ideas' } } },
)
src/Ideas.tsx
import type { Output } from 'sygnal/api'
import { suggest, save } from './ideas.server'
Ideas.model = {
SUGGEST: { HTTP: (state) => suggest({ tag: state.tag }, { ok: 'SUGGESTED' }) },
SUGGESTED: (state, { text }) => ({ ...state, draft: text }),
SAVE: { HTTP: (state) => save({ text: state.draft }, { ok: 'SAVED', error: 'FAILED' }) },
}
type Saved = Output<typeof save>
vite.config.ts
import { defineConfig } from 'vite'
import sygnal from 'sygnal/vite'
export default defineConfig({
plugins: [sygnal({ api: { functions: true, handler: 'server/api.ts' } })],
})

On the server, serverFunctions() turns the modules into an oRPC router. Sygnal still has no server: oRPC’s OpenAPIHandler serves it, with the same wire format as a contract:

server/api.ts
import { os } from '@orpc/server'
import { OpenAPIHandler } from '@orpc/openapi/fetch'
import { serverFunctions } from 'sygnal/api'
const functions = serverFunctions(import.meta.glob('/src/**/*.server.ts', { eager: true }), { os })
const handler = new OpenAPIHandler(functions.router)
export default async function handle(request: Request): Promise<Response> {
const skew = functions.skew(request)
if (skew) return skew
const { matched, response } = await handler.handle(request, { prefix: '/api', context: { user: await userOf(request) } })
return matched ? response : new Response('Not found', { status: 404 })
}
  • The path and the export name are the endpoint. src/ideas.server.ts is ideas, so suggest is ideas.suggest at POST /api/ideas/suggest. A query and a mutation are POSTs with a JSON body, so numbers stay numbers. A query is also tagged like a GET endpoint, so it works as a resource and with invalidates. stream(input, async function* (…) {…}) is a GET read as server-sent events, for connections; its input comes from the query string, so coerce non-string fields.
  • The client gets stubs. In client code, the plugin replaces the file with one stub per server function: its id, kind, declared error statuses and the file’s hash. The file’s imports (the database, API keys), the function bodies and its other exports never reach the bundle. The typed-api example’s tests build the client and search it for the server code and the key.
  • Only query, mutation and stream exports reach the client. A constant or a helper exported from the file is undefined in the client build, though it type-checks. sygnal-check reports that import, and a misspelled one (SYG691).
  • Validation is required. The first argument is a Standard Schema (zod, Valibot, ArkType). Leave it out for a function that takes no input: then only an empty input is accepted. output validates the reply too (each event of a stream), and errors declares errors by code: typed on the client like a contract’s, thrown with errors.CODE() on the server.
  • The second argument is oRPC’s handler options: context (what the server passes to handler.handle; type it with declare module 'sygnal/api' { interface ServerContext { user?: User } }), signal and errors.
  • Only module exports are server functions. Nothing inline in a component, and no closure over client values: what crosses the network is the validated JSON input.
  • Skew is checked per file. Each stub sends its file’s contract hash (x-api-functions: ideas:…), and functions.skew(request) answers 409 CONTRACT_SKEW when that file’s functions changed since the client was built. Calls to other files keep working. To compute the hash, the plugin loads the *.server.ts modules in Node at build time (and in the dev server), so keep their top level free of side effects: open connections on first use.
  • Tests: under Vitest the file keeps its code, and each export is also an endpoint. Answer a component’s call with the fakes, as for a contract (t.respond('HTTP', fixture(suggest, { text: 'Breathe.' }), suggest)), or run the real functions in-process through the handler.

Choose function-first for an app whose API has no other client. Choose a contract when the API is shared with other clients or teams, or when it is versioned on its own: the contract is then the API’s definition, and the server implements it.

Export
orpcClient(contract, options?)The oRPC router’s tree, with each procedure an endpoint
openApiClient<paths>(options?).get/.post/.put/.patch/.delete(path) and .sse<T>(path) → an endpoint
honoClient<Schema>(options?)The same, for Hono routes
optionsprefix (before every path), headers (on every request and stream), validate (oRPC: also check replies with the output schema on the client)
an endpoint(input?, options?) => request | connection, with id, kind ('query' | 'mutation' | 'stream'), method, path and match(request)
Output<E>, Input<E>, ErrorBody<E>, ApiFailure<E>, RawOutput<E>, Jsonify<T>Types
fixture(endpoint, data), errorFixture(endpoint, code, data?, message?)Test fixtures
contractHash(contract), contractSkew(request, { hash, header, require? }), isContractSkew(failure), contractFetch({ fetch?, onSkew? })Version skew
query(input?, fn, options?), mutation(…), stream(…)Function-first server functions in *.server.ts files; options: output, errors
serverFunctions(modules, { os, dir?, header? })On the server: { router, contract, hashes, skew(request) } for oRPC’s OpenAPIHandler
sygnal({ api })The Vite plugin: handler (served at prefix, default '/api', in dev), contracts (client modules without schemas), functions (true or { dir, header }: *.server.ts stubs)