Overview
Calls that overlap are handled in three ways:
- Identical reads in flight together reach the API once. Two components that read the same thing at the same moment — a header and a page both asking for the current user — send one request, and each gets the answer. This is on by default, wherever the call runs.
- A newer read can cancel the one it replaces. In a search box each keystroke makes the previous search pointless; turn
cancelPreviouson for such a read — on the call, the endpoint, its group, the client or the API. - Any call can be aborted with an
AbortSignalof your own.
Identical reads share one request
While a read is in flight, an identical read joins it rather than sending a request of its own. Every call that joined gets the answer — the same status, headers and body — as a copy of its own: one call editing what it got changes nothing for another.
// Both calls start before either answer arrives: the API receives one request.
const [user, sameUser] = await Promise.all([api.users.me(), api.users.me()])Two requests are identical only when everything they send is: the method, the address with its query, every header, and the body. Whatever tells two callers apart therefore keeps their requests apart:
- different variables — page 1 and page 2 are two requests;
- different users — their cookies,
Authorizationand address differ; - different requests being served, when the API keeps a session — its answer may start or renew the session of the visitor it was made for — or forwards each request's id with
forward: { requestId: true }.
On a server, one user's read is never answered with another's.
What is never shared:
- Writes. Two orders are two orders. A read is an endpoint addressed with
get,headorquery, or one marked.reads()— a search sent as a POST is joined too. - A request whose body is not text — a file, a form, a stream.
- A call that follows its upload or download progress, since each one reports its own.
- A call that reads its answer as a stream,
stream: true: one reader reads it as it arrives.
Studio shows each call, and marks one whose answer came from another call's request shared: its inspector says how — joined in flight, or read earlier in the render — and opens the call whose request answered it. Two components reading the user at once are two calls and one request. Every figure about the API — latency, pace, failures, statuses and bytes, in the Timeline, Analytics, the Explorer, the Audit, the status bar, a saved session and the editor's hints — counts the request alone, and names the calls beside it where the two differ, as 2 calls · 1 request; a failed or slow request is told in one toast, however many calls it answered. A HAR or a Postman collection holds the requests; a saved session and its JSON export keep every call, marked.
A request is joined only until its answer arrives. A read made after that sends a request of its own; to reuse an answer, keep it: React Query or SWR in the browser, the cache middleware on a server. In Next.js, createServerCaller already reads once per render: a page's generateMetadata and its body share the read even when one runs after the other.
Leaving early
A call that stops waiting — its signal aborted, its timeout reached — rejects alone, and the others still get the answer. The request itself is cancelled only when every call waiting for it has left.
Sending a call alone
Pass coalesce: false to send every call alone, for a whole API or for one call:
import { defineApi } from "@noverax/courier/define"
export const api = defineApi({
name: "telemetry",
baseURL: "https://telemetry.example.com",
coalesce: false,
endpoints: { /* ... */ },
})// Each poll asks the server anew, even while the last one is in flight
const status = await caller.jobs.with({ coalesce: false }).status({ id })Cancelling the previous call
A search as the user types makes every earlier search pointless the moment a new key is pressed. Turn cancelPrevious on for such a read, and a newer call of it cancels the older call still in flight — whatever its variables were:
import { courier, defineGroup } from "@noverax/courier/define"
const { endpoint } = courier()
type User = { id: string; name: string }
export const users = defineGroup({
prefix: "users",
endpoints: {
search: endpoint.get("search").variables<{ q: string }>().response<User[]>().cancelPrevious(),
},
})The cancelled call rejects with an AbortError whose code is "SUPERSEDED"; the newer one proceeds. A newer call identical to the one it cancels — the same search typed again — is answered by the request already in flight, so no second request goes out while coalesce is on, as it is by default. A middleware sees the error as it would any other, and the retry middleware never retries it. A call holds its endpoint from the moment it starts until it settles, its retries and the waits between them included: a newer call cancels an older one still getting ready to send, or waiting to try again, at once, and that call never sends.
Where to turn it on
cancelPrevious is true or false. It can be set at five levels; the nearest that sets it decides, and where none does, it is off:
| Where | How | What it covers |
|---|---|---|
| A call | .with({ cancelPrevious: true }) | the calls made through that .with() |
| An endpoint | .cancelPrevious(), or .cancelPrevious(false) | every call of it |
| A group | defineGroup({ cancelPrevious: true }) | the reads of the group, and of the groups inside it that set nothing |
| A client | cancelPrevious: true given to createCaller, createProxyCaller, createQueryCaller or createProxyQueryCaller | every read the client calls |
| The API | defineApi({ cancelPrevious: true }) | every read the API holds |
// The call itself says only its last answer matters
const found = await caller.geo.with({ cancelPrevious: true }).suggest({ q }).with() decides call by call even when given to a whole client: caller.with({ cancelPrevious: true }) decides over an endpoint's .cancelPrevious(false). To turn it on for a client beneath the endpoints' and groups' own, give it to the client's factory instead.
Only calls for which it is on take part: of two such calls to one endpoint, the newer cancels the older while that one is still in flight. A call for which it is off — false at whichever level decides — neither cancels another nor is cancelled. The clients of one API share what is in flight: every direct client of the API, and every proxy client given the same routes, so a hook's call and a call made outside the hooks cancel each other too.
Turned on for a whole API, a group or a client, it applies to any two overlapping calls of one endpoint: page 2 of a list cancels page 1, and a second card reading users.get cancels the first. Turn it on there when only the last answer of every read matters, and mark the exceptions with .cancelPrevious(false).
A proxy client reads the endpoint's and its groups' setting, and the API's own, from the routes Courier writes. Its own option decides over the API's alone — an endpoint's or a group's setting in the routes decides over it — and a call's .with() decides over all of them.
Only reads are cancelled
A write that a newer one superseded has usually reached the server and been applied, so cancelling it would tell its caller it failed when it did not. .cancelPrevious() on an endpoint that writes is a type error, and throws ConfigurationError CANCEL_PREVIOUS_ON_WRITE where it is written; a read sent as a POST says so with .reads() first. A call, a group, a client or an API that turns it on cancels reads alone.
A value other than true or false given to an API, a group or a client throws ConfigurationError CANCEL_PREVIOUS_INVALID where it is given, and so do routes that carry one; a call given one rejects with it. .cancelPrevious() turns it on with no argument or true, and off with any other.
Where it runs
A newer call cancels an older one where one user is: in a browser page, or in a React Native app, for a direct call and a proxy client alike. A Web Worker has no page, and calls made in one are not cancelled.
On a server the option has no effect — for direct calls, for a proxy client and for requests arriving at the proxy — save in the one case below: calls from different users reach the same endpoint there, and one user's search would cancel another's. A server that put a DOM on its global object for a library is a server still: a call made while a request is being served cancels none, and neither does any call of the server's caller, createCaller from @noverax/courier/server, nor of a proxy client that reaches the proxy in process. A call made there where no request is being served — a job's, a warm-up's — through the caller from @noverax/courier/client, or through a proxy client that goes to its proxy over HTTP, is taken for one user's, as in a page; give a job's calls .with({ cancelPrevious: false }), or make them with the server's caller.
In the query hooks
TanStack Query already cancels a query's request once its variables change and no component reads it any more, since the query hooks hand the request its signal. cancelPrevious serves the calls made outside the hooks. Turned on, it applies to the hooks' calls too: when two components read one endpoint with different variables at the same moment, the later call cancels the earlier, and the earlier query gets an HTTPError 499. Keep it off for an endpoint the hooks read that way, or pass requestOptions: { cancelPrevious: false } to the hook. The hooks never retry a query whose call a newer one cancelled, so the two cannot go on cancelling each other; any other failure is retried as the hook or its client says.
Handling the cancelled call
A cancelled call is no failure the user needs to hear about:
"use client"
import { isAbortError } from "@noverax/courier/client"
import { useState } from "react"
import { caller } from "@/lib/caller"
type User = { id: string; name: string }
export function SearchUsers() {
const [users, setUsers] = useState<User[]>([])
async function search(q: string) {
try {
// users.search is marked .cancelPrevious(): each keystroke cancels the search still in flight
setUsers(await caller.users.search({ q }))
} catch (error) {
if (isAbortError(error)) return // superseded by a newer search
console.error("Search failed:", error)
}
}
return (
<div>
<input onChange={(event) => search(event.target.value)} />
{users.map((user) => <p key={user.id}>{user.name}</p>)}
</div>
)
}Aborting a call yourself
Pass a signal with the call. It works on any call, alongside both of the above:
"use client"
import { isAbortError } from "@noverax/courier/client"
import { useEffect, useRef } from "react"
import { caller } from "@/lib/caller"
export function CancellableReport() {
const controllerRef = useRef<AbortController | null>(null)
async function generate() {
controllerRef.current?.abort()
controllerRef.current = new AbortController()
try {
const report = await caller.reports
.with({ signal: controllerRef.current.signal })
.generate({ type: "monthly" })
console.log("Report:", report)
} catch (error) {
if (isAbortError(error)) return
throw error
}
}
useEffect(() => () => controllerRef.current?.abort(), [])
return (
<div>
<button onClick={generate}>Generate report</button>
<button onClick={() => controllerRef.current?.abort()}>Cancel</button>
</div>
)
}A call aborted through your signal rejects with Courier's AbortError, whose code is "ABORTED" and whose cause is the reason you gave — the platform's DOMException named AbortError when you gave none — wherever the call was: before its request left, while it was out, while its answer was read, or while a middleware held it between attempts. A call a newer one superseded rejects the same way, with code "SUPERSEDED". On a call whose cancelPrevious is on, the call stops at whichever comes first — your signal, or a newer call. A cancellation is no failure: onError is not told of it, and no retry repeats it. A retry policy's deadline that runs out is a TimeoutError instead, as it is a failure.
Next steps
- Middleware — keep cancelled calls out of error reporting
- Options —
signal,timeout,coalesce,cancelPreviousand the other per-call options - Built-in middleware — the cache that keeps an answer after it arrives