Request
A Request is an immutable, typed description of one endpoint call: its endpoint, method, types and options. You create it once from the client and send it from components, servers, tests or scripts. It is plain data, so it can be cloned, serialized, queued while offline and restored later.
- Define an endpoint once with its response, payload, query params and error types.
- Send it anywhere with
send(), which always resolves with a response object. - Carry its behavior: cache, retries, cancelation, queueing and offline options.
import { client } from "./client";
export const getUser = client.createRequest<{ response: User }>()({
endpoint: "/users/:userId",
});
createRequest is called twice: the first call takes the types, the second the options. The split lets TypeScript
read :userId from the endpoint string and require it when you send.
Type the request
All generics are optional. Leave out what the endpoint does not have.
| Generic | Types |
|---|---|
response | data of a successful response |
payload | The body you send, set with setPayload or send({ payload }) |
queryParams | Query params. queryParams?: makes them optional, queryParams: required |
error | Endpoint errors, merged with the client's global error |
export const updateUser = client.createRequest<{
response: User;
payload: { name: string };
queryParams?: { notify?: boolean };
error: { fields: Record<string, string[]> };
}>()({ endpoint: "/users/:userId", method: "PATCH" });
TypeScript does not reject unknown keys in an object generic, so rsponse would pass silently. The
lint plugin reports it. When the endpoint is a typed GraphQL document, response
and payload come from it, see typed documents.
Pass params, query params and payload
Set values ahead of time with setters, or pass them to send(). Both are typed by the generics and the endpoint.
// Setters return a new request
const response = await updateUser
.setParams({ userId: 1 })
.setPayload({ name: "Ann" })
.send();
// Or all at once
await updateUser.send({
params: { userId: 1 },
payload: { name: "Ann" },
queryParams: { notify: true },
});
- Params come from
:namesegments of the endpoint. A missing one is a compile error. - Query params are serialized by the adapter. The fetch adapter's array format and encoding are set with
client.adapter.setQueryParamsMapperConfig. - Payload can be JSON data or
FormData. Falsy values like0or""are sent as they are,nullremoves the payload.
Guides: parameters, query params and payload.
Setters return a clone
Every setter returns a new request and leaves the original untouched. Use the returned value. The mock setters
(setMock, clearMock, setMockingEnabled) are the only exception: they change the instance.
getUser.setParams({ userId: 1 }); // result discarded
await getUser.send(); // compile error: params are still required
await getUser.setParams({ userId: 1 }).send(); // correct
Send it
send() goes through the dispatcher, the adapter and the cache. It resolves with
{ data, error, status, success, extra, requestTimestamp, responseTimestamp } for every outcome, including HTTP errors,
timeouts and aborts, so you never need try/catch. The one exception is throwOnError, below.
const { data, error, status } = await getUser.send({ params: { userId: 1 } });
if (data) console.log(data.name);
else console.error(status, error);
send() accepts every request option except endpoint and method, plus these:
| Option | Default | Description |
|---|---|---|
cachePolicy | "network-only" | "cache-first" returns a cached entry, fresh or stale, else fetches. "revalidate" returns the cached entry and refetches in the background. |
dispatcherType | "auto" | "auto" sends GET and QUERY through fetchDispatcher, the rest through submitDispatcher. Force one with "fetch" or "submit". |
optimistic | none | Optimistic changes for this call only. |
signal | none | An AbortSignal that aborts only this call. Also taken by exec(). |
Neither cache policy looks at staleTime. request.read() returns the cached response without a network call.
exec() sends straight through the adapter: interceptors, mappers, lifecycle callbacks and $hooks run, but there is
no deduplication, queue, retry, offline handling or cache write. Use it for one-off server calls, or when TanStack Query
or SWR owns the cache. See the fetching guide.
throwOnError makes send() and exec() reject with the error of a failed response, for code that expects a
rejected promise. A successful response resolves as usual. It is a request option, default false: change it per call,
with setThrowOnError(true), or for many requests with client.adapter.setRequestDefaults.
const { data } = await getUser.exec({
params: { userId: 1 },
throwOnError: true,
});
Control how it is sent
The dispatcher reads these options from the request. Each has a setter, such as setCancelable(true).
| Option | Default | What it does |
|---|---|---|
deduplicate | true for GET and QUERY ¹ | Identical requests in flight share one call |
cancelable | false | A new send aborts the previous one with the same queryKey |
queued | false | Requests with the same queryKey go one at a time, in order |
offline | true | Requests wait for the connection instead of failing |
retry | 0 | Failed attempts to retry, delayed by retryTime (default 500 ms) |
- The fetch adapter turns deduplication on for GET and QUERY. Other methods and adapters default to
false.
Abort in-flight requests with request.abort(), which aborts every request with the same abortKey. To abort one call,
pass signal to send() or exec(): it triggers the controller of that call only, and a queued call is never sent.
Decide per response whether to retry with setRetryOnError:
const getReport = client
.createRequest()({ endpoint: "/reports", retry: 3, retryTime: 1000 })
// skip retries for 4xx
.setRetryOnError(({ status }) => !!status && status >= 500);
Guides: cancellation, deduplication, queueing, offline and retries.
Keys
Three keys tie a request to the cache, the queues and aborting. They are derived from the request, so equal requests share cache entries and deduplication automatically.
| Key | Identifies | Default value | Example for GET /users/1?page=2 | Setter |
|---|---|---|---|---|
cacheKey | The cached response | method, filled endpoint, query params | GET_/users/1_{"page":2} | setCacheKey |
queryKey | The dispatcher queue | method, filled endpoint, query params | GET_/users/1_{"page":2} | setQueryKey |
abortKey | Requests aborted together | method, endpoint template, cancelable | GET_/users/:userId_false | setAbortKey |
Override a key to group requests on purpose. For search-as-you-type, give a cancelable request one queryKey, because
the default one changes with every query:
const searchUsers = getUsers.setCancelable(true).setQueryKey("users-search");
To change how keys are built for every request, use client.setCacheKeyMapper, setQueryKeyMapper or
setAbortKeyMapper. The mapper must return a key for every request, so fall back to getRequestKey(request).
Scope requests on the server
setScope(id) prefixes all three keys with the scope, so scoped requests never share cache, queues or aborts. On a
client in "server" mode a request is only cached when it has a scope. See Cache.
const { data } = await getUser
.setParams({ userId: 1 })
.setScope(session.id)
.send();
Map and validate
setResponseMapperreshapes or validates the response and changes the type ofdata. A throw becomes an error response. The cache keeps the raw response.setRequestMapperchanges the request right before it is sent. A throw stops the request and returns an error.setPayloadMappertransforms the payload, for example intoFormData.
const getProfile = client
.createRequest<{ response: { full_name: string } }>()({ endpoint: "/me" })
.setResponseMapper((response) => {
if (!response.data) return response;
return { ...response, data: { name: response.data.full_name } };
});
Guides: data mapping, mapping and validation.
Update the cache optimistically
setOptimistic changes cached data before the server answers. Build each change with optimistic(). Core rolls it back
on failure, abort or removal from the queue, and refreshes the target once the last pending change on it settles.
import { optimistic } from "@hyper-fetch/core";
export const toggleTodo = client
.createRequest<{ response: Todo; payload: { done: boolean } }>()({
endpoint: "/todos/:todoId",
method: "PATCH",
})
.setOptimistic(({ params, payload }) => [
optimistic(getTodos).patch(params.todoId, payload),
]);
The callback can also return { updates, context, rollback, invalidate }. The
optimistic updates guide covers every field.
Listen to the lifecycle
send() takes callbacks for one call. $hooks registers listeners on the request instance, which run for every
send() and exec() of it and of clones made afterwards. Each $hooks method returns an unsubscribe function.
await getUser.send({
params: { userId: 1 },
onRequestStart: ({ requestId }) => console.log("started", requestId),
onDownloadProgress: ({ progress }) => console.log(progress),
onRetry: ({ retry, delay }) => console.log(`retry ${retry} in ${delay} ms`),
onResponse: ({ response }) => console.log(response.status),
});
const unsubscribe = getUser.$hooks.onResponse(({ response }) =>
track(response.status),
);
The callbacks are onBeforeSent, onRequestStart, onResponseStart, onUploadProgress, onDownloadProgress,
onRetry, onResponse and onRemove. A callback that throws does not break the request: send() still resolves and
the error is thrown from a timer, where window.onerror or uncaughtException handlers see it. $hooks are not part
of toJSON().
Methods
| Name | Description |
|---|---|
| Reconstruct a Request instance from a previously serialized JSON representation. |
| Serialize the request configuration into a plain JSON object for persistence or transfer. |
| Mark the request as used (prevents automatic refetching in hooks). |
| Make
send()
and
exec()
reject with the
error
of a failed response instead of resolving with it - for the
query functions of React Query, the fetchers of SWR and other code which tells failures by a rejected promise. |
| Enable or disable structural sharing - keeping references of unchanged parts of the response data in cache. |
| Set how long (in ms) cached data is considered fresh before triggering a revalidation. |
| Set a scope identifier for this request. All keys (cache, queue, abort) are prefixed with this scope, isolating the request from other scopes. In "server" client mode, setting a scope also enables caching (which is otherwise disabled to prevent cross-request leaks). |
| Set the delay in milliseconds between retry attempts, or a function that returns it for each attempt. |
| Set a callback that controls whether a failed request should be retried.
Called on each failed attempt before scheduling the next retry.
Return
true
to allow the retry,
false
to stop retrying immediately. |
| Set the number of retry attempts on failure. |
| Map the response to the new interface |
| Map request before it gets send to the server |
| Set whether the request should be queued and executed sequentially rather than immediately. |
| Set the query parameters appended to the URL. |
| Override the query key that identifies this request in the dispatcher queue. |
| Map data before it gets send to the server |
| Set the request body payload. Passing
null
removes the payload set before. |
| Set the URL path parameters (e.g.,
:userId
). |
| Set adapter-specific options (e.g., axios config, fetch init). |
| Configure optimistic update behavior for this request.
The callback runs before the request is sent and receives
{ request, client, payload, params, queryParams, optimistic }
. A synchronous callback changes the cache within the
send()
call.Return an array of changes built with
optimistic()
.rollback()
on final failure, abort or queue removal, and refreshes the targets after the last pending mutation
on them. Or return an object with
updates
,
context
(available in lifecycle callbacks as
mutationContext
),rollback
(called once on failure, abort or queue removal),
invalidate
(requests invalidated on success),rollbackOnError
and
revalidate
.
Everything runs for every way of sending the request, not only inside of framework hooks. |
| Set whether the request should be stored in the offline queue when there is no network connection. |
| Enable or disable the mocker for this request without removing the mock handler. |
| Attach a mock handler to this request. When mocking is enabled, the handler is called instead of the real adapter. |
| Set the request headers. Returns a cloned request with the new headers applied. |
| Set the time window (in ms) during which identical requests are deduplicated. |
| Enable or disable request deduplication. When enabled, concurrent identical requests share a single response. |
| Set whether in-flight requests with the same abort key are cancelled when a new one is dispatched. |
| Set how long (in ms) the response remains in cache before being garbage collected. |
| Override the cache key used to store/retrieve the response. |
| Set whether this request should use the cache. |
| Set whether authentication interceptors should run for this request. |
| Override the abort key used to cancel this request. |
| Read the response from cache dataIf it returns error and data at the same time, it means that latest request was failed and we show previous data from cache together with error received from actual request |
| Extract the current cache data for this request into a portable hydration payload (useful for SSR). |
| Create a new request instance with optional configuration overrides. Used internally by all setter methods. |
| Remove any attached mock handler and disable mocking for this request. |
| Abort all in-flight requests sharing this request's abort key. |
| send | Method used to perform requests with usage of cache and queues |
| exec | Send the request straight to the adapter, WITHOUT the dispatcher and the cache: it is not queued, deduplicated,
retried or cached. Lifecycle callbacks,
$hooks
, interceptors and the response mapper work like in
send()
.
Use it when something else owns caching and retries, like React Query or SWR - with
signal
and
throwOnError
. |
Options
| Name | Type | Description |
|---|---|---|
| abortKey | | Key which will be used to cancel requests. Autogenerated by default. |
| auth | | Should the onAuth method get called on this request (default true) |
| cache | | Should we save the response to cache |
| cacheKey | | Key which will be used to cache requests. Autogenerated by default. |
| cacheTime | | Should we trigger garbage collection or leave data in memory |
| cancelable | | Should enable cancelable mode in the Dispatcher |
| deduplicate | | Should we deduplicate two requests made at the same time into one |
| deduplicateTime | | Window in milliseconds, counted from the start of the in-flight request, in which a new request joins it.
Default
null
: a deduplicated request joins any matching request that is still in flight. |
| disableRequestInterceptors | | Disable pre-request interceptors |
| disableResponseInterceptors | | Disable post-request interceptors |
| endpoint | | Determine the endpoint for the request |
| headers | | Custom headers for request |
| method | | Request method picked from method names handled by adapter With default adapter it is GET | POST | PATCH | PUT | DELETE |
| offline | | Do we want to store request made in offline mode for latter use when we go back online (default true) |
| options | | Options passed to the adapter. For the default
HttpAdapter
these are
fetch
options such as
timeout
,responseType
and
streaming
. |
| queryKey | | Key which will be used to queue requests. Autogenerated by default. |
| queued | | Should the requests be queued and sent one-by-one |
| retry | | Retry count when request is failed |
| retryTime | | Delay in milliseconds before a retry, or a function that returns it for each attempt - for exampleexponentialBackoff()
. A function is not kept when the request is serialized for a persistent queue. |
| staleTime | | Time for which the cache is considered up-to-date |
| structuralSharing | | Keep references of the unchanged parts of the response data when saving it to cache (default true). Deeply equal responses keep the previous data reference, which limits rerenders and recalculations. |
| throwOnError | | Make
send()
and
exec()
reject with the
error
of a failed response instead of resolving with it - for code
which tells failures by a rejected promise, like the query functions of React Query or the fetchers of SWR. A
successful response resolves the same way as without it. The thrown value is not typed, narrow it where you catch
it. Set it per request, for many requests with the adapter's
setRequestDefaults
, or per call. |
- Define each endpoint once with
createRequest<Types>()(options)and keep it at module level. - Setters return a new request.
send()always resolves with{ data, error, status }. cacheKey,queryKeyandabortKeyare derived from the request and decide cache, queues and aborting.
Next steps
Runnable examples: Fetch on click, Typed errors, Response mapping and Cancellation.