Skip to main content
Version: v10.5.0

Request

Read the API Reference »

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.

Purpose
  1. Define an endpoint once with its response, payload, query params and error types.
  2. Send it anywhere with send(), which always resolves with a response object.
  3. Carry its behavior: cache, retries, cancelation, queueing and offline options.
api/users.ts
import { client } from "./client";

export const getUser = client.createRequest<{ response: User }>()({
endpoint: "/users/:userId",
});
Send a request

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.

GenericTypes
responsedata of a successful response
payloadThe body you send, set with setPayload or send({ payload })
queryParamsQuery params. queryParams?: makes them optional, queryParams: required
errorEndpoint errors, merged with the client's global error
api/users.ts
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.

src/update-user.ts
// 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 :name segments 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 like 0 or "" are sent as they are, null removes 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.

src/get-user.ts
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.

src/get-user.ts
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:

OptionDefaultDescription
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".
optimisticnoneOptimistic changes for this call only.
signalnoneAn 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.

src/get-user.ts
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).

OptionDefaultWhat it does
deduplicatetrue for GET and QUERY ¹Identical requests in flight share one call
cancelablefalseA new send aborts the previous one with the same queryKey
queuedfalseRequests with the same queryKey go one at a time, in order
offlinetrueRequests wait for the connection instead of failing
retry0Failed attempts to retry, delayed by retryTime (default 500 ms)
  1. 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.

Cancel the previous call

Decide per response whether to retry with setRetryOnError:

api/reports.ts
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.

KeyIdentifiesDefault valueExample for GET /users/1?page=2Setter
cacheKeyThe cached responsemethod, filled endpoint, query paramsGET_/users/1_{"page":2}setCacheKey
queryKeyThe dispatcher queuemethod, filled endpoint, query paramsGET_/users/1_{"page":2}setQueryKey
abortKeyRequests aborted togethermethod, endpoint template, cancelableGET_/users/:userId_falsesetAbortKey

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:

api/users.ts
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.

src/get-user.ts
const { data } = await getUser
.setParams({ userId: 1 })
.setScope(session.id)
.send();

Map and validate​

  • setResponseMapper reshapes or validates the response and changes the type of data. A throw becomes an error response. The cache keeps the raw response.
  • setRequestMapper changes the request right before it is sent. A throw stops the request and returns an error.
  • setPayloadMapper transforms the payload, for example into FormData.
api/profile.ts
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.

api/todos.ts
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.

src/get-user.ts
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​

Methods
Name Description
fromJSON(client, json)
Reconstruct a Request instance from a previously serialized JSON representation.
toJSON()
Serialize the request configuration into a plain JSON object for persistence or transfer.
setUsed(used)
Mark the request as used (prevents automatic refetching in hooks).
setThrowOnError(throwOnError)
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.
setStructuralSharing(structuralSharing)
Enable or disable structural sharing - keeping references of unchanged parts of the response data in cache.
setStaleTime(staleTime)
Set how long (in ms) cached data is considered fresh before triggering a revalidation.
setScope(scopeId)
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).
setRetryTime(retryTime)
Set the delay in milliseconds between retry attempts, or a function that returns it for each attempt.
setRetryOnError(callback)
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.
setRetry(retry)
Set the number of retry attempts on failure.
setResponseMapper(responseMapper)
Map the response to the new interface
setRequestMapper(requestMapper)
Map request before it gets send to the server
setQueued(queued)
Set whether the request should be queued and executed sequentially rather than immediately.
setQueryParams(queryParams)
Set the query parameters appended to the URL.
setQueryKey(queryKey)
Override the query key that identifies this request in the dispatcher queue.
setPayloadMapper(payloadMapper)
Map data before it gets send to the server
setPayload(payload)
Set the request body payload. Passing null removes the payload set before.
setParams(params)
Set the URL path parameters (e.g., :userId ).
setOptions(options)
Set adapter-specific options (e.g., axios config, fetch init).
setOptimistic(callback)
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()
  • core applies them, runs their .commit() on success or
.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.
setOffline(offline)
Set whether the request should be stored in the offline queue when there is no network connection.
setMockingEnabled(isMockerEnabled)
Enable or disable the mocker for this request without removing the mock handler.
setMock(fn, config)
Attach a mock handler to this request. When mocking is enabled, the handler is called instead of the real adapter.
setHeaders(headers)
Set the request headers. Returns a cloned request with the new headers applied.
setDeduplicateTime(deduplicateTime)
Set the time window (in ms) during which identical requests are deduplicated.
setDeduplicate(deduplicate)
Enable or disable request deduplication. When enabled, concurrent identical requests share a single response.
setCancelable(cancelable)
Set whether in-flight requests with the same abort key are cancelled when a new one is dispatched.
setCacheTime(cacheTime)
Set how long (in ms) the response remains in cache before being garbage collected.
setCacheKey(cacheKey)
Override the cache key used to store/retrieve the response.
setCache(cache)
Set whether this request should use the cache.
setAuth(auth)
Set whether authentication interceptors should run for this request.
setAbortKey(abortKey)
Override the abort key used to cancel this request.
read()
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
dehydrate(config)
Extract the current cache data for this request into a portable hydration payload (useful for SSR).
clone(configuration)
Create a new request instance with optional configuration overrides. Used internally by all setter methods.
clearMock()
Remove any attached mock handler and disable mocking for this request.
abort()
Abort all in-flight requests sharing this request's abort key.
sendMethod used to perform requests with usage of cache and queues
execSend 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​

RequestOptionsType
Name Type Description
abortKey
string
Key which will be used to cancel requests. Autogenerated by default.
auth
boolean
Should the onAuth method get called on this request (default true)
cache
boolean
Should we save the response to cache
cacheKey
string
Key which will be used to cache requests. Autogenerated by default.
cacheTime
number
Should we trigger garbage collection or leave data in memory
cancelable
boolean
Should enable cancelable mode in the Dispatcher
deduplicate
boolean
Should we deduplicate two requests made at the same time into one
deduplicateTime
number
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
boolean
Disable pre-request interceptors
disableResponseInterceptors
boolean
Disable post-request interceptors
endpoint
GenericEndpoint
Determine the endpoint for the request
headers
HeadersInit
Custom headers for request
method
RequestMethods
Request method picked from method names handled by adapter With default adapter it is GET | POST | PATCH | PUT | DELETE
offline
boolean
Do we want to store request made in offline mode for latter use when we go back online (default true)
options
AdapterOptions
Options passed to the adapter. For the default HttpAdapter these are fetch options such as timeout ,responseType and streaming .
queryKey
string
Key which will be used to queue requests. Autogenerated by default.
queued
boolean
Should the requests be queued and sent one-by-one
retry
number
Retry count when request is failed
retryTime
RetryTimeType
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
number
Time for which the cache is considered up-to-date
structuralSharing
boolean
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
boolean
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.


Summary
  • 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, queryKey and abortKey are derived from the request and decide cache, queues and aborting.

Next steps​

Runnable examples: Fetch on click, Typed errors, Response mapping and Cancellation.

Fetching
How send() and exec() run a request, step by step.
Cache
How responses are stored, refreshed and invalidated.
TanStack Query and SWR
Call requests from useQuery, useMutation and useSWR.
Request API reference
Every method and property of the Request class.