Import
import { defineApi } from "@noverax/courier/define"Signature
declare function defineApi<G extends OwnGroups>(
options: BaseOptions & { groups: G }
): DefinedApi<G>groups takes any name but raw or with, and the flat endpoints any name but options, raw, with or __proto__: see Reserved names. A reserved name is a type error and throws ConfigurationError("RESERVED_ENDPOINT_NAME") when the source is defined.
Parameters
BaseOptions
The core configuration for a data source:
type BaseOptions = {
baseURL?: string
responseType?: "json" | "text" | "blob" | "arrayBuffer" | "formData"
responseParser?: ResponseParser
defaultBody?: Record<string, unknown>
defaultQueryParams?: Record<string, unknown>
allowedHeaders?: string[]
bodySerializer?: (data: Record<string, unknown>) => BodyInit
searchParamsSerializer?: SearchParamsSerializer
coalesce?: boolean
cancelPrevious?: boolean
middleware?: Middleware[]
pathOptions?: PathOptions
timeout?: number
headers?: HeadersInit
signal?: AbortSignal
session?: SessionOptions
forward?: ForwardOptions
}Basic Usage
With Groups
import { defineApi } from "@noverax/courier/define"
import { users } from "./users"
import { posts } from "./posts"
const api = defineApi({
baseURL: process.env.API_URL ?? "http://localhost:4000",
groups: { users, posts },
})
export const sources = { api }
export type Sources = typeof sourcesWith Options
import { defineApi } from "@noverax/courier/define"
import { logMiddleware, authMiddleware } from "@noverax/courier/middleware"
const api = defineApi({
baseURL: process.env.API_URL ?? "http://localhost:4000",
// Response parsing (default: "json")
responseType: "json",
// Default data merged into every POST/PUT/PATCH body
defaultBody: { apiKey: process.env.API_KEY },
// Default params merged into every request
defaultQueryParams: { locale: "en" },
// Request timeout in milliseconds
timeout: 10_000,
// Static headers
headers: {
"X-Client": "courier",
Authorization: `Bearer ${process.env.API_SECRET}`,
},
// Middleware chain
middleware: [
logMiddleware(),
authMiddleware({ getToken: () => getAuthToken() }),
],
groups: { users, posts },
})Options Reference
baseURL
Sets the base URL prefix for all requests from this source.
responseType
Controls response parsing. Supported: "json" (default), "text", "blob", "arrayBuffer", "formData". A 204 status always returns null. A proxy client resolves to the same kind of value as a direct call.
responseParser
Turns each answer's body, read as responseType, into what a call resolves to — an error answer's too, the data of its HTTPError. It is handed the body Courier read — JSON already parsed, or the text, the Blob, the bytes, the form — and the answer's status and headers, and may return a promise:
const api = defineApi({
baseURL: "...",
responseType: "text",
responseParser: (text, { headers }) =>
headers.get("content-type")?.includes("xml")
? new DOMParser().parseFromString(String(text), "text/xml")
: text,
groups: { users },
})Courier reads the body itself, the way it reads every answer, so a call that is cancelled, runs out of time or shares its request with another gives up its read or reads its own copy. An answer whose status has no body resolves to null without the parser, and a call that names its own responseType has its successful answer read as that, without the parser; its error answers are still read as the source's. What the parser throws fails the call with an HTTPError of the answer's status; a Courier error it throws is thrown as it is.
defaultBody
Object merged into every POST/PUT/PATCH body:
const api = defineApi({
baseURL: "...",
defaultBody: { apiKey: "...", version: "v2" },
groups: { users },
})
// POST /users body: { apiKey: "...", version: "v2", name: "Alice" }defaultQueryParams
Object merged into every request's search parameters:
const api = defineApi({
baseURL: "...",
defaultQueryParams: { locale: "en", format: "json" },
groups: { users },
})
// GET /users → GET /users?locale=en&format=jsonmiddleware
Array of middleware functions applied to every request. See Middleware.
bodySerializer
Custom body encoder (e.g., for URL-encoded forms):
const api = defineApi({
baseURL: "...",
bodySerializer: (data) =>
new URLSearchParams(Object.entries(data).map(([k, v]) => [k, String(v)])),
groups: { users },
})searchParamsSerializer
Custom search params encoder:
import qs from "qs"
const api = defineApi({
baseURL: "...",
searchParamsSerializer: {
stringify: (obj) => qs.stringify(obj),
parse: (str) => qs.parse(str),
},
groups: { users },
})coalesce
Identical reads in flight together share one request — the same method, address, headers and body, every credential among them — and each call gets a copy of the answer. On by default; false sends every call of the API alone, and a call can say so for itself with .with({ coalesce: false }). Writes are never shared. See Deduplication & Abort.
cancelPrevious
Whether a newer call of one of the API's reads cancels the older call of that read still in flight — a search as the user types, where only the last answer matters. The older call rejects with an AbortError of code "SUPERSEDED", whatever its variables were. Off unless something turns it on. true turns it on for every read the API holds, so page 1 and page 2 of a list loaded together cancel each other too; it is usually set nearer — on an endpoint with .cancelPrevious(), on a group, on a client or on one call — and the nearest that sets it decides. A write is never cancelled. It runs in a browser or a React Native app, where one user is; on a server it has no effect, but for the calls a server that put a DOM on its global object takes for one user's — see Deduplication & Abort. A value other than true or false throws ConfigurationError CANCEL_PREVIOUS_INVALID where the API is defined.
allowedHeaders
Additional header names the proxy carries for every endpoint of the source, in both directions: forwarded from the browser to the backend, and passed back from the backend's answer to the browser. An endpoint names its own with .headers([...]), which adds to this list rather than replacing it. The lists govern only what the proxy passes along: headers the source, a middleware or an endpoint's own closure sets are written by you and are always sent, and a browser's copy of one of them is dropped rather than sent in its place.
const users = defineGroup({
prefix: "users",
endpoints: {
list: endpoint.get("").headers(["x-total-count", "link"]),
create: endpoint.post("").headers(["location"]),
},
})Cookies are named the same way, one direction at a time: cookie forwards the caller's cookies to the upstream, and set-cookie passes the upstream's back. Neither crosses where it is not named — see Cookies. An API that keeps a session names its cookies there instead, and refuses cookie and set-cookie in these lists with SESSION_HEADER_CONFLICT: they would carry every cookie past it.
The headers that describe the body — Content-Type, Content-Length, Content-Encoding — are never taken from these lists, because the proxy sends a body of its own.
session
How the API keeps the user's session: the cookies it is kept in, by name or by a prefix ending in *; a cookie holding a bearer token; the double-submit token a write repeats; whether the session cookies it sets reach the browser; the other origins whose pages may make writes with it. A call made while a server serves a user carries that user's session from the request being served; a call made in a browser lets the browser send its own cookies.
defineApi({
baseURL: "https://api.example.com",
session: {
cookies: ["sessionid", "logto_*"],
bearer: "access_token",
csrf: { cookie: "csrftoken", header: "x-csrftoken" },
},
endpoints,
})An endpoint takes it with session: false when it answers every user alike, and session: "unguarded" for a write that does no harm when another site sets it off, such as signing out. See User Sessions.
A session that could not work as written is refused with a ConfigurationError before any call, whatever NODE_ENV says, on every way a server calls the API with a request: as its sources are registered, as a handler is made with them — the proxy route's, a socket's, the MCP server's — as the server's caller or a Server Action is made, as ensureCsrfToken gives a page its token, and at the first call the server lends a request's session to, whichever caller made it. A page and a React Native app check one of these themselves, as each call goes: a call that would carry the session over plain HTTP across the public internet is refused with SESSION_INSECURE_TRANSPORT before anything is sent. Every caller checks SESSION_OTHER_ORIGIN as each request of a call goes. A page's and an app's definitions check none of them:
| Code | When |
|---|---|
SESSION_OPTIONS_INVALID | An option a session does not have, a cookie name no browser keeps, a header no request carries, no credential named at all, or a session that is no plain data |
SESSION_INSECURE_TRANSPORT | The API is reached over plain HTTP across the public internet, and allowHttp is not set |
SESSION_OTHER_ORIGIN | A request of a call that takes the session would go to another origin than the API's: an endpoint's absolute URL, or a .via() closure, names another host, or, off a page, neither the API nor the call names an address at all. Give that host an API of its own, the API its baseURL, or the endpoint { session: false } |
SESSION_HEADER_CONFLICT | The API's allowedHeaders, or an endpoint's .headers(), names cookie or set-cookie, which would carry every cookie past the session |
FORWARD_OPTIONS_INVALID | An option forward does not have, a header it may not carry, or a forward that is no plain data |
HEADER_LIST_INVALID | The API's allowedHeaders, or an endpoint's .headers(), is no list of header names: a Set, say |
INVALID_ALLOWED_ORIGIN | An allowedOrigins entry no page's Origin can equal |
Once a server has taken the API up, it holds what it checked: in place of the API's session, forward and header lists, and of each endpoint's .headers() and .agent(), the options give a copy frozen to its depths, read once, as the check read it — the objects and the lists as you wrote them, which code that reads the options back reads as it did before — and an option the API did not name is held unset. None of them is changed or set later — doing so throws a TypeError. The objects given to defineApi stay yours, and a change made to them later reaches no call. Options put in the place of the API's or an endpoint's, and an endpoint the API is given later, are checked and held the same way before a call takes them, an endpoint too as the sources are registered again. A call reads its API's options once, as it is made, and takes what the server holds of those wherever it goes — the headers of the request it forwards, those its answer hands the browser, the address a stream opens at — so options put in their place while it is on its way are the next call's, and a server sends only what it checked. These options are data, objects of plain data and lists of strings. A server reads every option a call is made with as its own properties alone — the API's, its groups' and its endpoints', the call's own and its caller's context and defaults, those it checks and those it does not, fetch, redirect, baseURL and headers among them — as a page's caller made on a server does, and defineApi, defineGroup and an endpoint's builder read a definition so: what a prototype answers for a key they do not have, Object.prototype among them, is none of theirs, changes nothing of the call and opens no endpoint .expose() did not mark. Courier tells a page, an app and a server apart by what the platform itself defines — a page's own window and document, the platform's location, React Native's own navigator.product — and never by what Object.prototype answers for those names: a server given them there follows no redirect to another origin, and its calls through /client stay many users', none cancelling another's or taking a page's or an app's token. What Courier hands the platform says itself each key the platform reads of it: an answer names its status, status text and headers, a stream's source and strategy stand on no prototype, and so does a request, which on Node names its referrer, referrerPolicy, mode, credentials, cache, integrity, keepalive and window too, as the platform's defaults have them, but a call of the server's caller or of the proxy's handler, whose credentials is omit — Node reads those of Object.prototype where a request does not name them, of the objects it builds of the request, and sends a referrer it finds there as the request's Referer. What the platform reads of the objects it builds itself is its own, and each key it takes from Object.prototype does as follows. Node's fetch takes a dispatcher, a signal and a body there whatever request it is handed, and a redirect where the call names none: the server's calls fail. The stream Node makes of an answer's body takes an autoAllocateChunkSize, on Node 22 a cancel too: no answer with a body is built. Each socket Node opens takes a highWaterMark: no connection is made, the application's own server's among them. Those are refusals, not leaks. Node's answers take their status and statusText there too, and nothing that reads an answer can tell: a status no answer has fails every call, but one an answer may have is every answer's — an answer the upstream refused reads as that status, so a server's caller takes its body for the data, and the proxy hands it on with that status. An instance of a class, a Map or a Set in their place is refused. In options you froze yourself no copy can take an option's place, so a server takes one there only frozen to its depths, and refuses it otherwise with the code of its check; options you sealed are held as any are.
forward
The headers a call made while serving a request carries from it. An endpoint keeps them off its calls with forward: false; how they travel with the user's session is in User Sessions.
| Option | What it carries |
|---|---|
requestId | The request's own x-request-id — the id nginx's $request_id, a load balancer or a platform wrote, so each API's logs join your application's — when it is one: up to 200 visible characters, none a quote or a backslash. Otherwise an id made for it. Every call made while serving the request carries the same id, on every attempt a retry makes. A header's name names another header; several — ["x-request-id", "x-correlation-id"] — are each sent the id, read from the first the request carries one in. |
trace | W3C traceparent and tracestate, when the request carries a valid one and no OpenTelemetry tracer in the process propagates it already. |
clientAddress | The user's address as X-Forwarded-For: the chain the proxies in front recorded, with the address of the one that connected. A header's name, or several — ["x-real-ip", "x-client-ip"] — are each sent the user's address alone as well, for an API that reads it from one header; naming x-forwarded-for sends it there in place of the chain, and forwarded as RFC 7239's for=. See The user's address. |
userAgent | The user's browser, as User-Agent. |
locale | The user's languages, as Accept-Language. |
headers | Further headers of the request, by name — a tenant, a region your edge added. Credentials, connection headers and the headers that claim a client's address cannot be listed: a request could have written them itself; clientAddress sends the user's address in those. |
Related
- User Sessions — the session and the forwarded headers, end to end
- defineGroup — defining endpoint groups
- Defining APIs Guide — in-depth usage patterns
- Middleware — middleware reference