Courier ships six production-ready middleware functions. Import them from @noverax/courier/middleware:
import {
retryMiddleware,
authMiddleware,
logMiddleware,
rateLimitMiddleware,
cacheMiddleware,
headerVariablesMiddleware,
} from "@noverax/courier/middleware"retryMiddleware
Sends a failed attempt again, as a retry policy says — the same policy an endpoint's .retry() and a courier() base's retry take. Its defaults follow the standard retry mode of the AWS SDKs: a few retries, random waits that grow, a ceiling on any one wait, an answer's Retry-After honoured, and a budget that stops retrying an upstream that keeps failing.
declare function retryMiddleware(options?: RetryOptions): Middleware
interface RetryOptions {
/** How many times a failed attempt is made again (default: 3, at most 10) */
limit?: number
/** The wait before the first retry, in ms (default: 300) */
delay?: number
/** How the wait grows between retries (default: "exponential", doubling it) */
backoff?: "fixed" | "exponential"
/** "full" waits a random time up to the wait, "none" the wait itself (default: "full") */
jitter?: "full" | "none"
/** The longest one wait may be, in ms; an answer asking for longer is not retried (default: 20000) */
maxDelay?: number
/** The most time the attempts and the waits between them may take, in ms (default: none) */
deadline?: number
/** Which failures deserve another attempt (default: "network" but a refused certificate and undici's own headersTimeout and bodyTimeout, and 408, 425, 429, 500, 502, 503, 504) */
retryOn?: readonly (number | "network" | "timeout")[] | ((failure: RetryFailure) => boolean)
/** Retry endpoints that write as well as those that read (default: a write with an idempotency key, or one that never left) */
mutations?: boolean
/** Told before each retry: the attempt it makes, the wait before it, and why */
onRetry?: (retry: RetryEvent, ctx: MiddlewareContext) => unknown
/** Where the jitter's randomness comes from (default: Math.random) */
random?: () => number
}
/** Why an attempt failed, as retryOn is shown it */
type RetryFailure =
| { kind: "status"; status: number; data: unknown; headers: Headers } // an answer that was not a success
| { kind: "network"; error: NetworkError } // no answer came
| { kind: "timeout"; error: TimeoutError } // the attempt's time ran out
/** A retry the policy is about to make */
interface RetryEvent {
attempt: number // 2 for the first retry
delay: number // the wait before it, in ms
failure: RetryFailure // why the attempt before it failed
}const api = defineApi({
baseURL: "https://api.example.com",
middleware: [
retryMiddleware({ limit: 3, deadline: 10_000 }),
],
groups: { /* ... */ },
})RetryOptions, RetryEvent and RetryFailure are exported from @noverax/courier/middleware as types. An endpoint's .retry() loads the policy's code with the endpoint's first call, so a page whose endpoints retry nothing does not carry it.
What is retried
Where retryOn says nothing:
| An attempt that failed with | Retried | Why |
|---|---|---|
No answer at all — a NetworkError | yes | a dropped or refused connection, a host that did not resolve: the next attempt may get through |
A certificate the platform refused — a NetworkError | no | no second attempt mends it |
| 408, 425, 429 | yes | the server gave up waiting, the request came too early, too many came at once |
| 500, 502, 503, 504 | yes | failures an upstream may get over |
| 501 and every other status | no | the same request would be refused again |
Its own time running out — a TimeoutError | no | a slow upstream would only be made slower; name "timeout" in retryOn to retry it |
The runtime's own wait for an upstream that took the request — undici's headersTimeout or bodyTimeout, a NetworkError with the systemCode UND_ERR_HEADERS_TIMEOUT or UND_ERR_BODY_TIMEOUT | no | the same: a slow upstream would only be made slower; name "network" in retryOn to retry it |
| A response that fails its schema, a middleware that throws | never | whatever retryOn says |
A redirect an upload cannot follow — one its call refuses with redirect: "error", one more than 20 hops in, one to another scheme — a NetworkError | never | the upstream would answer it with the same redirect, whatever retryOn says |
Give retryOn the statuses of answers, "network" for a request that got no answer, "timeout" for one whose time ran out — or a test of why the attempt failed:
retryMiddleware({ retryOn: ["network", "timeout", 429, 502, 503, 504] })
retryMiddleware({
retryOn: (failure) =>
failure.kind === "network" ||
(failure.kind === "status" && failure.headers.get("x-retryable") === "true"),
})A list takes the default's place. Its "network" is every request that got no answer, a refused certificate and undici's own headersTimeout and bodyTimeout among them, which the default leaves out, so the default written out as a list retries those too.
What the condition sees
A non-2xx answer rejects the call with an HTTPError; retryOn is shown the answer it carries — its status, body and headers. A request that got no answer rejects with a NetworkError, shown as kind: "network", and one whose time ran out with a TimeoutError, shown as kind: "timeout", each with the error. A success is never shown to it. After the last attempt, its error is re-thrown.
The waits
| Option | Default | |
|---|---|---|
limit | 3 | retries after the first attempt; at most 10 |
delay | 300 ms | the wait before the first retry |
backoff | "exponential" | the wait doubles with each retry; "fixed" keeps it |
jitter | "full" | each wait is a random time up to the delay; "none" waits the delay itself |
maxDelay | 20 s | no wait is longer; an answer asking for longer is not retried |
With the defaults, the three waits are random times up to 300 ms, 600 ms and 1.2 s. Random waits spread out the clients an outage failed at once, so they do not all come back at once and fail the recovering upstream again. With limit: 10, the waits stop growing at 20 s rather than reaching minutes. Pass random to make the waits predictable in a test.
An answer with a Retry-After header is waited for as it asks instead of the backoff — a 429 from a rate limiter is asked again when it says. The header is read in seconds, a fraction such as 1.5 too, or as an HTTP date in any of the three forms HTTP has for one, a date already past asking for no wait; a value that is neither, an ISO date among them, is not read, and the backoff applies. One that asks for longer than maxDelay is not retried: the call fails at once with that answer, and its caller decides what to do.
A deadline for the whole call
deadline bounds the attempts and the waits between them together, counted from the first attempt. No wait starts that would end past it: the call fails with the last failure instead. An attempt still running when the deadline passes is stopped, and the call rejects with a TimeoutError whose scope is "deadline", which is never retried. An endpoint's .timeout() still limits each attempt on its own.
retryMiddleware({ limit: 5, deadline: 10_000 }) // five retries at most, ten seconds in allThe retry budget
The calls a policy retries share a budget, as the AWS SDKs keep one: a retry spends 5 of 500, a retry after a timeout 10, and a call that is answered gives back what its last retry spent — or 1, when it needed none. A retry that is never sent, its call cancelled while it waited, costs nothing. While an upstream keeps failing, the retries stop once the budget is spent and every call fails after its first attempt, rather than piling onto an upstream that is trying to recover; answers fill the budget again. Each retryMiddleware() has a budget of its own; the .retry() policies of one API's endpoints share one.
Told of each retry
onRetry is told before each wait: the attempt it is about to make, the wait, and why the attempt before it failed. It is the place to log or count retries. A promise it returns is waited for before the wait begins, but no longer than the call is: the deadline ends the call with its TimeoutError while the promise is pending, and a cancellation with an AbortError, the promise left to settle on its own. An onRetry that throws or rejects fails the call with its error:
retryMiddleware({
onRetry: ({ attempt, delay, failure }, ctx) => {
console.warn(`${ctx.method}: attempt ${attempt} in ${delay} ms, after ${failure.kind}`)
},
})Writes are sent once — unless they carry a key
An endpoint that writes — a post, put, patch or del, named on the chain or called by a .via() closure, that .reads() did not declare a read, or any endpoint .writes() declared a write — is not retried by default. A write whose answer was lost may already have been carried out, and sending it again can charge a card twice.
An endpoint that declares an idempotencyKey is retried: each call sends one key in that header, the same on every attempt, and an upstream that deduplicates by it applies the write once however many times it arrives.
place: endpoint
.post("orders", { idempotencyKey: "header:Idempotency-Key" })
.retry({ limit: 3 }) // retried: the key makes a repeated write safeA write that certainly never left is retried too, since the upstream never saw it: its host had no address (ENOTFOUND, EAI_AGAIN) or no route (ENETUNREACH, EHOSTUNREACH), or refused the connection (ECONNREFUSED) or did not take it in time (UND_ERR_CONNECT_TIMEOUT). A browser names no such code, so there such a write is sent once.
mutations: true retries every write, for an upstream that recognises a repeated one some other way; mutations: false retries none, keys and writes that never left included:
retryMiddleware({ limit: 3, mutations: true })A retry policy on a courier() base or an endpoint's .retry() follows the same rule and takes the same mutations flag. Middleware reads a call's key as ctx.idempotencyKey, and Studio lists it with the call, and where it stands among the calls sent with the same key. A call whose body is a stream, which cannot be sent twice, is sent once.
Cancellations
A cancellation is never retried, whatever retryOn says: not a call whose signal the caller aborted, whatever reason it gave, and not a read that a newer call of its endpoint superseded because its cancelPrevious was on — an AbortError of code "SUPERSEDED". A call cancelled while the middleware waits between attempts, or just after an attempt failed, is answered at once with an AbortError, not with the failure it no longer waits on — so a read a newer call superseded never sends again.
A policy is checked as it is made
A policy that cannot work is refused with a ConfigurationError whose code is RETRY_OPTIONS_INVALID: an option it does not have, a limit past 10, a wait or a deadline that is no number of milliseconds or longer than a timer keeps — 2³¹ − 1 ms, about 24.8 days, past which it fires at once — or a retryOn naming what no failure is — 0 among them, which once stood for a request that got no answer. retryMiddleware() refuses it where it is called; an endpoint's .retry() and a base's retry on the endpoint's first call, which is then refused before it is sent. The types refuse most of these as they are written.
authMiddleware
JWT/OAuth token injection with automatic refresh on 401.
type GivenToken = string | null | undefined
declare function authMiddleware(options: {
/** Gives the current token before each attempt: null, undefined or "" when there is none */
getToken: () => GivenToken | Promise<GivenToken>
/** Gives a new token when the upstream answers 401: null or undefined when it cannot */
refreshToken?: () => GivenToken | Promise<GivenToken>
/** Refuse a call with no token before it is sent, with a MissingTokenError (default: false) */
required?: boolean
/** Header name (default: "Authorization") */
header?: string
/** Auth scheme the token follows (default: "Bearer"; "" sends the token alone) */
scheme?: string
}): MiddlewareBasic usage
const api = defineApi({
baseURL: "https://api.example.com",
middleware: [
authMiddleware({
getToken: () => localStorage.getItem("access_token"),
}),
],
groups: { /* ... */ },
})Before there is a token
A call made while there is no token — getToken gives null, undefined or "" — goes without the header, so a page signs in through the very API whose middleware sends the token; a header the call set itself is left as it is. With required: true, such a call is refused before it is sent, with a MissingTokenError whose header names the header it needed:
import { isMissingTokenError } from "@noverax/courier/client"
const account = authMiddleware({ getToken: () => session.accessToken, required: true })
try {
await caller.account.get()
} catch (error) {
if (isMissingTokenError(error)) redirect("/sign-in")
}Through the proxy, the browser is answered 401 with { "success": false, "message": …, "code": "TOKEN_MISSING" }, as an upstream that wanted a token would answer, and the server's log stays quiet: a visitor who has not signed in is no failure of the server.
A token holding a control character other than a tab, a line break inside it among them, or a character past U+00FF, which no header can carry, is refused before the request leaves with a ConfigurationError of code HEADER_VALUE_INVALID, and the error never repeats the token; a line break at its end, as a file read whole leaves one, is trimmed as fetch trims it. A header that is no header name, a scheme that is no auth scheme, or an option the middleware does not have is refused where the middleware is made, with code AUTH_OPTIONS_INVALID.
With token refresh
When refreshToken is provided and the upstream answers 401, the middleware calls refreshToken(), updates the header, and sends the request again once. If the new token is refused too, the call rejects with that second 401, and so it does with the first when refreshToken() gives no token or the request's body is a stream that cannot be sent twice. One refresh serves every call refused with the token it renews: a call refused with that token while the refresh runs waits for it, and one sent with it before the refresh ended takes the refresh's token, so refreshToken() runs once however the refusals fall — a hundred calls sent at once with an expired token cost one refresh. A refresh that fails rejects the calls waiting on it with its error, and the next 401 tries again:
authMiddleware({
getToken: () => tokenStore.accessToken,
refreshToken: async () => {
const { accessToken } = await refreshAccessToken(tokenStore.refreshToken)
tokenStore.accessToken = accessToken
return accessToken
},
})A refresh is shared by token, never between tokens. On a server, where getToken and refreshToken read the user of the request being served — from its cookies, or an AsyncLocalStorage — each user's calls renew that user's token, and a call refused with one user's token is never sent again with another's. A call sent without a token refreshes for itself. A refresher remembers the last 100 tokens it renewed.
A call sent with a token after its refresh ended refreshes again, so a refresh token that may be used only once needs more of refreshToken. On a server, a request the browser sent before it stored the renewed cookies carries the old ones, and arrives once the refresh has ended; an identity provider that rotates refresh tokens may take the second use of one for a stolen copy and end the session. There refreshToken renews once for each refresh token, and answers one it has just spent with the renewal it gave, for as long as such requests may come — kept where every replica reads it, where there are several. The middleware does not do it for you: it would let an expired token, a leaked one among them, be sent again with its successor.
getToken and refreshToken are waited for no longer than the call is, as onRetry is: a call cancelled while one of them has not answered rejects at once with its AbortError, and one past the deadline of a retry policy around the middleware with that TimeoutError; a refresh other calls wait for goes on for them. A call's timeout bounds each request it sends, not them: a token source that may hang — one that renews the token over the network — bounds its own wait, as with AbortSignal.timeout() on its fetch.
API key authentication
Set scheme to an empty string and use a custom header for non-Bearer auth:
authMiddleware({
getToken: () => process.env.API_KEY,
header: "X-API-Key",
scheme: "",
required: true, // a missing key is a mistake of the deployment, refused before anything is sent
})logMiddleware
Request/response logging with timing information.
declare function logMiddleware(options?: {
/** Receives each line, and the error of a failed request (default: Courier's logger) */
logger?: (message: string, error?: unknown) => void
}): MiddlewareLogs each request as source:group:method → status (duration). On errors, logs source:group:method → ERROR (duration) and passes the error along. By default the lines go to Courier's logger: a success at info on stdout, a failure at warn on stderr with the error's stack.
const api = defineApi({
baseURL: "https://api.example.com",
middleware: [
logMiddleware(),
],
groups: { /* ... */ },
})
// Output:
// api:users:getAll → 200 (42ms)
// api:users:create → 201 (89ms)
// api:auth:login → ERROR (1203ms)Custom logger
Send logs to your observability platform:
import * as Sentry from "@sentry/node"
logMiddleware({
logger: (message) => {
Sentry.addBreadcrumb({ category: "api", message })
},
})rateLimitMiddleware
Client-side rate limiting. Delays requests that exceed the configured limit within a time window.
declare function rateLimitMiddleware(options: {
/** Maximum number of requests in the window */
maxRequests: number
/** Time window in milliseconds */
window: number
}): Middlewareconst api = defineApi({
baseURL: "https://api.example.com",
middleware: [
rateLimitMiddleware({ maxRequests: 10, window: 1000 }),
],
groups: { /* ... */ },
})Queuing, not rejecting
Unlike server-side rate limiters that return 429 errors, this middleware delays requests until the window allows them. Your code does not need to handle rate limit errors -- the middleware transparently queues requests.
The limit holds however many calls arrive at once: at most maxRequests requests go out in any window milliseconds, and calls beyond it wait their turn in the order they came. The window is measured from when each request actually went, so a busy event loop that runs the limiter's timers late delays the queue rather than letting several requests out together. A caller that aborts its signal leaves the queue at once and rejects with an AbortError, its signal's reason as the cause; its turn passes to the call queued behind it.
cacheMiddleware
In-memory response caching with configurable TTL.
declare function cacheMiddleware(options: {
/** How responses are partitioned between callers: "public", "session", or a function naming the caller */
scope: "public" | "session" | ((ctx: MiddlewareContext) => string)
/** Time-to-live in milliseconds (default: 60000) */
ttl?: number
/** Entries retained before the oldest are dropped (default: 1000) */
maxEntries?: number
/** Custom storage; a Map satisfies it (default: in-memory, per middleware instance) */
storage?: CacheStore
}): MiddlewareCaches successful responses (2xx status) of endpoints that read, keyed by the scope's partition, source:group:method and the variables. Non-2xx responses are never cached, nor the answers to a request the session makes for itself, such as the double-submit token a write asks for: it is made for the cookie its answer sets.
const api = defineApi({
baseURL: "https://api.example.com",
middleware: [
cacheMiddleware({ scope: "public", ttl: 30_000 }), // 30 seconds
],
groups: { /* ... */ },
})Every caller receives a copy of its own, made with structuredClone, so editing a result never changes what the next caller gets. An answer holding a value that cannot be copied, such as a function, is not cached; class instances come back as plain objects.
Calls that miss together — a burst on an entry that is empty or has just expired — reach the API once: the first fetches, and the others wait for its answer and take a copy, as a hit would. One that stops waiting leaves at once while the others go on. When the first one's answer is not kept — an error, a Set-Cookie — each of the others makes its own call.
A call that carries the user's session is never answered from a "public" cache, nor stored in it: its answer belongs to that user, and the endpoint is named once in the log. Give such an API's per-user reads a cache of their own with scope: "session" — one partition per set of credentials the call sends, its Cookie and its Authorization, named by their SHA-256 digest so the credentials never sit in a store's keys:
cacheMiddleware({ scope: "session", ttl: 10_000 })An API with no session of its own sends the credentials its middleware adds, and the cache reads them where it stands in the chain: put it after the middleware that adds them, such as authMiddleware. Placed before it, the cache sees none, so every call reaches it as one without credentials, and the partition those share answers them all: for up to ttl a signed-in user's call is answered with what a guest's call fetched, and never reaches authMiddleware. The cache keeps no answer a call was sent with credentials added further in, so no user is served another's, and it names the endpoint once in the log when such a call misses — while a guest's answer is kept, no call misses, and nothing is logged.
In a browser or a React Native app, the platform sends the session's cookies itself, out of a script's reach. There, every call of an API with a session counts as carrying it, so a "public" cache keeps none of its answers, and scope: "session" partitions by what a script can read — a bearer token, the double-submit token an API renews with the session — and starts a new partition with every write made with the session, as it starts and once it is answered. A user who signs out and another who signs in on the same device, in the same tab or another, never share a cached answer, nor see one read while the sign-in was under way.
Custom storage
Provide your own Map instance to control the cache externally (e.g., for manual invalidation):
const apiCache = new Map()
const api = defineApi({
baseURL: "https://api.example.com",
middleware: [
cacheMiddleware({ scope: "public", ttl: 60_000, storage: apiCache }),
],
groups: { /* ... */ },
})
// Invalidate the entire cache
function invalidateCache() {
apiCache.clear()
}Variables affect the cache key
Two requests to the same endpoint with different variables produce different cache keys. users:getById with { id: 1 } and { id: 2 } are cached separately.
headerVariablesMiddleware
Sends some of a call's variables as request headers instead of in its path, query or body: an API's header parameters, such as a digest or a version the caller picks per call. Generated clients use it for the header parameters an OpenAPI document declares.
declare function headerVariablesMiddleware(names: readonly string[]): Middlewareimport { courier, defineApi } from "@noverax/courier/define"
import { headerVariablesMiddleware } from "@noverax/courier/middleware"
const { endpoint } = courier()
export const api = defineApi({
baseURL: "https://api.example.com",
endpoints: {
find: endpoint
.get("things")
.variables<{ q: string; "X-Digest"?: string }>()
.use(headerVariablesMiddleware(["X-Digest"])),
},
})import { createCaller } from "@noverax/courier/server"
import { api } from "./sources"
// GET /things?q=red, with the header X-Digest: sha-256=abc
await createCaller(api).find({ q: "red", "X-Digest": "sha-256=abc" })The variables are validated whole, then the named ones are taken out and set as headers under their own names; one left unset sends no header. A list is written comma-separated and an object as its keys and values in turn, as OpenAPI's simple style writes a header. Each value is written as JSON writes it, its own toJSON asked first, so a direct call and a call through the proxy send the same header: a date is its ISO string, and a value JSON leaves out or writes as null — NaN, a date that is no date — sends no header. A file, a Set, a Map or a BigInt is refused with a ConfigurationError whose code is VARIABLE_NOT_ENCODABLE before anything is sent. For a call through the proxy it runs in your application's server, so the values travel with the variables and the browser sets no such header itself. A value no header carries — a control character other than a tab, a line break inside it among them, or a character past U+00FF — fails the call's variables as a value their schema refuses does: a ValidationError whose issue names the variable, answered 422 through the proxy, with nothing sent and the value not repeated.
Composing Built-in Middleware
Order matters. Place middleware in the array from outermost to innermost:
import { defineApi } from "@noverax/courier/define"
import {
authMiddleware,
cacheMiddleware,
logMiddleware,
rateLimitMiddleware,
retryMiddleware,
} from "@noverax/courier/middleware"
const api = defineApi({
baseURL: "https://api.example.com",
middleware: [
logMiddleware(), // 1. Log everything
retryMiddleware({ limit: 3, delay: 300 }), // 2. Retry on failure
authMiddleware({ getToken: () => getToken() }), // 3. Attach the user's token
cacheMiddleware({ scope: "session", ttl: 30_000 }), // 4. Return the user's cached answer
rateLimitMiddleware({ maxRequests: 10, window: 1000 }), // 5. Throttle what goes out
],
groups: { /* ... */ },
})The cache comes after authMiddleware, since its partition is named by the token the call carries at the cache's place, and the rate limit after the cache, so that an answer the cache gives counts against no limit.
Next Steps
- Custom Middleware -- write your own middleware
- Middleware Overview -- the onion model and core types