Import
import { createCaller } from "@noverax/courier"@noverax/courier gives the server's caller, wherever it runs, and so does @noverax/courier/server; a page or an app takes its own from @noverax/courier/client. Where a bundler or a test environment takes the core's modules for a page — the browser condition, which Jest's jsdom environment names, and Node's --conditions=browser — the root's caller is a page's, as in a page, and the caller of @noverax/courier/server is refused as it is made, with ConfigurationError SERVER_CAPABILITY_MISSING, rather than made one whose calls carry the page's session: test server code in a node environment. The server's caller lends the calls of its process what only a server does — the user's session, read from the request a call's context names or the one an adapter serves, and the addresses that request came through — and checks the options only a server reads as it is made: session, forward, the header lists beside a session and .agent(), whatever NODE_ENV says. A page's caller carries none of that code, and its calls carry the cookies the browser sends, each call refused before it goes when it would carry them over plain HTTP across the public internet. On a server, it takes what the server lent once a handler was made, the sources registered, the server's caller or a Server Action made, or the framework's request context registered with registerRequestContext or served with withIncomingRequest, and the server checks the same options at the first call it lends a request's session to. Where nothing was, a call of an API that keeps a session or forwards headers, whose context names a request, is refused with ConfigurationError SERVER_CAPABILITY_MISSING, naming the endpoint, rather than sent without the user's credentials; the refusal says what to do on a server, and what else it finds: code built for a page, or another copy of the core under another contract.
Signature
createCaller takes your API definition and optional defaults, returning a TypedClient. Direct mode calls the backend directly without going through a proxy.
import type { CallerDefaults, TypedClient } from "@noverax/courier/client"
import type { DefinedApi } from "@noverax/courier/define"
declare function createCaller<TApi extends DefinedApi>(
api: TApi,
defaults?: CallerDefaults,
): TypedClient<TApi>Parameters
api
An API source definition created with defineApi().
import { api } from "@/api"
const caller = createCaller(api)CallerDefaults
Optional default settings applied to every request.
type CallerDefaults = {
timeout?: number
cancelPrevious?: boolean
headers?: Record<string, string>
context?: Context
onError?: (error: RequestFailure) => void | Promise<void>
onSuccess?: (data: unknown) => void | Promise<void>
ws?: CallerWSOptions
}
type CallerWSOptions = {
auth?: WSAuthParams | (() => WSAuthParams | undefined | Promise<WSAuthParams | undefined>)
backoff?: { initialMs?: number; maxMs?: number; factor?: number; jitter?: boolean }
fallback?: false | { after?: number; remember?: boolean }
messageQueue?: { maxCount?: number; maxBytes?: number; overflow?: "reject" | "drop-oldest" }
protocols?: string[]
reconnectOnResume?: boolean
}
type WSAuthParams = Record<string, unknown>cancelPrevious turns on, for every read this caller makes, a newer call cancelling the older call of the same read still in flight — where the endpoint and its groups say nothing; it decides over the API's own. It runs in a browser or a React Native app; on a server it has no effect, and the server's caller's calls cancel none of each other, a server's with a DOM on its global object too. See Deduplication & Abort.
ws— options of the sockets this caller's channels and push subscriptions open; see Connection options.
Return Type
A call resolves to the response data. Through .raw it resolves to the whole response, HttpResponse<R>, with status, headers and data; with .with({ stream: true }) the data is the unread ReadableStream.
type HttpResponse<T> = {
status: number
headers: Headers
data: T
}Basic Usage
import { createCaller } from "@noverax/courier/server"
import { api } from "@/api"
export const caller = createCaller(api, {
timeout: 10000,
})
// Usage: caller.group.method(variables?)
const result = await caller.users.getAll()
const user = await caller.users.getById({ id: "123" })Streams and channels
A direct caller opens a stream or a channel at the API's baseURL, as it sends any other call there. One served by this process with .implement() is not at baseURL — that is the upstream's address — so calling it through createCaller throws ConfigurationError("DIRECT_CALL_TO_SERVED_ENDPOINT"), naming the endpoint, when it is called; the rest of the API stays callable. Reach it through createProxyCaller and the server that serves it — see Streams & Channels.
Passing Context
defaults.context is a Context object. Use it to forward headers from the incoming request to the backend: authorization, user-agent, referer, origin and x-request-id, the headers the source and the endpoint name, and the user's cookies where they name cookie. A context belongs to one incoming request, so build the caller for that request:
type Context = {
req?: Request
res?: Response
headers?: Headers
}import { createCaller } from "@noverax/courier/server"
import { api } from "@/api"
export async function GET(req: Request) {
// The session the API describes is read from this request
const caller = createCaller(api, { context: { req } })
const profile = await caller.users.getProfile()
// Headers of your own, for one call
const user = await caller.users
.with({ headers: { "x-tenant": "acme" } })
.getById({ id: "123" })
return Response.json({ profile, user })
}An API that keeps a session takes the user's session from the request a context names, and a framework adapter finds that request without one — see User Sessions. Handing a caller await headers() whole sends the API every header and every cookie the browser addressed to your application.
Server Components
Direct mode is designed for server-only execution. Use it in React Server Components, API routes, server actions, or any backend runtime.
import { caller } from "@/lib/caller"
export default async function UsersPage() {
const result = await caller.users.getAll()
return (
<ul>
{result.data?.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
)
}Server Actions
"use server"
import { caller } from "@/lib/caller"
import { revalidatePath } from "next/cache"
export async function createUser(formData: FormData) {
const name = formData.get("name") as string
await caller.users.create({ name })
revalidatePath("/users")
}Configuring Defaults
const caller = createCaller(api, {
timeout: 15000,
headers: {
"X-Internal-Service": "courier-app",
},
onError: (error) => {
if (isHTTPError(error)) console.error(`[Direct] HTTP ${error.status}:`, error.data)
else console.error(`[Direct] ${error.message}`) // a NetworkError or a TimeoutError
},
})Related
- Server-Side Usage — direct mode architecture
- Server Actions — mutations with revalidation
- createProxyCaller — proxy-mode alternative for client components
- defineApi — defining data sources