This site counts visits with analytics cookies only if you accept. Read the consent

Skip to content

API ReferencecreateProxyCaller

createProxyCaller

Factory function that creates a typed client with dot-notation access for proxy-mode HTTP calls from the browser.

7 min readUpdated proxy mode

Import

ts
import { createProxyCaller } from "@noverax/courier/client"

Signature

createProxyCaller takes the routes of an API — the endpoints a page may call and how it reaches each, as Courier's plugin for your build gives them to the page from the endpoints marked .expose() — and options, and returns a typed client. The routes carry the type of the API they were read from, so the client has its groups, methods, variables and response types, for the endpoints the routes name alone.

ts
import type { InferClient, ProxyCallerOptions } from "@noverax/courier/client"
import type { CourierRoutes, RoutedApi, RouteShape } from "@noverax/courier/define"

declare function createProxyCaller<TApi, TEndpoints extends Readonly<Record<string, RouteShape>>>(
  routes: CourierRoutes<TApi, TEndpoints>,
  options?: ProxyCallerOptions,
): InferClient<RoutedApi<TApi, TEndpoints>>

Parameters

routes

The routes of one API — routes.api from @noverax/courier/routes for the source registered as api, or apiRoutes from courier.routes.ts. See Exposing Endpoints for how Courier gives them, and how to write them by hand in a project without a courier.config.ts. Routes whose cancelPrevious is neither true nor false are refused with ConfigurationError("CANCEL_PREVIOUS_INVALID") when the client is made; the plugin, or courier-cli routes, gives them again.

ts
interface CourierRoutes<TApi, TEndpoints> {
  source: string                    // the name the server registered the API under
  endpoints: TEndpoints             // each endpoint a page may call, by its path, and how it is reached
  cancelPrevious?: boolean          // the API's own cancelPrevious
  coalesce?: boolean                // the API's own coalesce
}

type RouteShape =
  | { type: "query"; get?: true; cancelPrevious?: boolean } // a read; GET when it may be cached; its endpoint's or groups' cancelPrevious
  | { type: "mutation" }            // a write
  | { transport: "sse" }            // a server-sent event stream
  | { transport: "ws"; bidirectional?: true } // a socket; one the caller also sends on

ProxyCallerOptions

All fields are optional.

ts
type ProxyPath = {
  http?: string  // default: "/api/request"
  sse?: string   // default: "/api/sse"
  ws?: string    // no default — required for WS endpoints
}

type ProxyCallerOptions = {
  proxyPath?: ProxyPath
  timeout?: number
  cancelPrevious?: boolean
  coalesce?: boolean
  credentials?: RequestCredentials
  headers?: Record<string, string>
  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>
  • proxyPath — where the app serves its proxy routes, per transport. Each field accepts either a relative path, resolved against the page's origin, or an absolute URL; a missing one falls back to the built-in default. The routes do not say it: it depends on where the page is served.
  • cancelPrevious — whether a newer call of one of the client's reads cancels its call still in flight to the same endpoint; the cancelled call rejects with an AbortError of code "SUPERSEDED". An endpoint's .cancelPrevious() and its groups' own, which the routes carry, and a call's .with({ cancelPrevious }) decide over it. Defaults to the API's own, which the routes carry too. Only a read the routes name is ever cancelled, and only in a browser or a React Native app — see Deduplication & Abort.
  • coalesce — whether identical reads in flight together reach the proxy once, each call with a copy of the answer. On by default; false sends every call alone. Defaults to the API's own, which the routes carry.
  • timeout — how long the browser waits for the proxy, in milliseconds. It is not sent to the server, so the endpoint's own .timeout() still bounds the upstream call; a timeout given with .with() for one call is sent.
  • credentials — whether the browser sends its cookies to the proxy route, with every call and stream. Defaults to "include". The proxy forwards them to the backend only where the source or the endpoint names cookie — see Cookies.
  • headers — default headers merged into every request and stream, and sent in the first frame of every socket its channels open, which the proxy reads as the socket's own — a browser cannot put them on a WebSocket's handshake.
  • onError — global error handler invoked on every HTTPError.
  • onSuccess — global success handler invoked on every successful response.
  • ws — options of the sockets this caller's channels and push subscriptions open; see Connection options.

WS has no default path

proxyPath.ws has no built-in default. Calling a WS endpoint without it throws ConfigurationError("WS_PATH_NOT_CONFIGURED", ...). In runtimes that cannot host WebSocket upgrades in-process (Next.js App Router, Cloudflare Workers, Vercel Edge, AWS Lambda), point this at a running @noverax/courier-server instance.

Return Type

Returns InferClient<RoutedApi<TApi, TEndpoints>> — the client of the API with the endpoints the routes name alone, a group they name nothing in left out:

  1. Group access — caller.users — accesses the endpoint group.
  2. Endpoint execution — caller.users.getById({ id: "123" }) — executes an endpoint with its variables, its only argument; an endpoint without variables takes none.
  3. Per-call options — caller.users.with({ timeout: 5_000 }).getAll() — headers, a timeout or a signal for the calls made through it; .raw resolves to the whole response instead of its body.

Each call resolves to what reaches the page: the proxy sends what the endpoint gave on as JSON, so the call is typed Proxied<T> of it — the endpoint's own type where JSON keeps it whole, a Date as its ISO string, and so on, as Mapping the answer lists. So is each event of a stream or a channel.

An endpoint the routes do not name is not on the type. Called anyway — from JavaScript, or past a cast — the client throws ConfigurationError("ENDPOINT_NOT_IN_ROUTES", ...) before anything is sent, since the proxy would refuse it.

Basic Usage

lib/caller.ts
import { createProxyCaller } from "@noverax/courier/client"
import { routes } from "@noverax/courier/routes"

const caller = createProxyCaller(routes.api, {
  timeout: 10000,
  credentials: "include",
})

// Dot-notation: caller.group.method(variables)
const users = await caller.users.getAll()
const user = await caller.users.getById({ id: "123" })

Configuring Options

lib/caller.ts
import { createProxyCaller, isHTTPError } from "@noverax/courier/client"
import { routes } from "@noverax/courier/routes"

const caller = createProxyCaller(routes.api, {
  // Per-transport proxy endpoint paths.
  // A missing transport falls back to its built-in default.
  proxyPath: {
    http: "/api/courier",                         // override default /api/request
    sse: "/api/sse",                              // default
    ws: "wss://realtime.example.com",             // required for WS endpoints
  },

  // Request timeout in milliseconds
  timeout: 15000,

  // Cookie handling (default: "include")
  credentials: "include",

  // Default headers for every request
  headers: {
    "X-App-Version": "1.0.0",
    "Accept-Language": "en",
  },

  // Global error handler: an HTTPError, a NetworkError or a TimeoutError
  onError: (error) => {
    if (isHTTPError(error) && error.status === 401) {
      window.location.href = "/login"
    }
  },

  // Global success handler
  onSuccess: (data) => {
    console.log("Request succeeded:", data)
  },
})

Per-Request Options

Name CallOptions with .with(), then call the endpoint:

ts
const user = await caller.users
  .with({
    timeout: 5000,
    signal: controller.signal,
    method: "POST", // Keep this call's variables out of the address
  })
  .getById({ id: "123" })

Upload Progress

Pass onUploadProgress to track file upload progress. When set, Courier uses XMLHttpRequest for real network-level progress tracking.

ts
const result = await caller.files
  .with({
    onUploadProgress: (progress) => {
      console.log(`${Math.round(progress.percent * 100)}%`)
    },
  })
  .upload(formData)

XHR Transport

When onUploadProgress is set, Courier uses XMLHttpRequest instead of fetch to provide real network-level progress tracking on both HTTP/1.1 and HTTP/2.

Files go in a FormData, or in a field of a record of variables, which travels as a record upload that the server restores. Any other variables travel to the proxy as JSON, so a call whose variables hold binary data where no form carries it — deeper than a field, a stream — is refused before it is sent, with ConfigurationError("VARIABLE_NOT_ENCODABLE", ...) naming where it sits — see the upload guide.

The progress covers the browser's upload to the proxy route. The proxy then forwards the whole file to your backend, so the call resolves after progress has reached 100% — see progress in proxy mode.

GET or POST

A read that may be cached — one that declares .cache() and whose variables are not sensitive, which the routes mark get: true — goes to the proxy as GET, its variables as JSON in the _v parameter of the address, so a browser or a CDN can reuse the answer its .cache() allows. Every other call goes as POST, its variables in the body: GET would gain nothing for a read that nothing on the way may keep, and POST keeps the variables of every other read out of the address.

ts
// search declares .cache({ revalidate: 60 }):
// GET /api/request?_s=api&_g=users&_m=search&_v={"q":"ada"}
const found = await caller.users.search({ q: "ada" })

// POST /api/request?_s=api&_g=users&_m=create, body {"variables":{"name":"Jane"}}
const user = await caller.users.create({ name: "Jane" })

A read that may be cached goes as POST all the same when its variables carry a body — form data, an upload whose progress is watched — or would make the address longer than 2 KB, which some servers and CDNs refuse. An address is written down by every access log it passes, so a read whose variables must not be — an email address, a search someone typed — declares sensitiveVariables, and always goes as POST, whatever its .cache(); the proxy refuses it over GET:

ts
byEmail: endpoint.get("customers", { sensitiveVariables: true }).variables<{ email: string }>()

A call can still ask for either verb with .with({ method: "GET" }) or .with({ method: "POST" }); a write asked for over GET is refused 405, and so is a read whose variables are sensitive.