HyperFetch on the server
A Node.js script with no framework and no UI. It loads users from dummyjson, fetches their
posts in parallel and shows how retries treat a server error and a client error. npm run dev runs it with tsx, and
the preview is the terminal output.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { client, getStatus, getUserPosts, getUsers } from "./api.js";
const started = performance.now();
const log = (message: string) =>
console.log(`${`${Math.round(performance.now() - started)}ms`.padStart(7)} ${message}`);
console.log(`HyperFetch on ${process.release.name} ${process.version}, client mode: ${client.mode}\n`);
// 1. A typed request. `send()` never throws: the result holds either `data` or `error`.
const { data, error, status } = await getUsers.send();
if (!data) {
console.error("Could not load users:", error?.message);
process.exit(1);
}
const { users } = data;
log(`GET /users -> ${status}, ${users.map((user) => `${user.firstName} ${user.lastName}`).join(", ")}`);
// 2. Parallel requests: one per user, all in flight at once.
log(`Fetching the posts of ${users.length} users in parallel`);
const posts = await Promise.all(
// `select` is a dummyjson query param: the API returns only these fields.
users.map((user) => getUserPosts.setParams({ userId: user.id }).setQueryParams({ limit: 2, select: "title" }).send()),
);
posts.forEach((response, index) => {
const titles = response.data?.posts.map((post) => `"${post.title}"`).join(", ") || response.error?.message || "none";
log(` ${users[index].firstName}: ${response.data?.total ?? 0} posts, ${titles}`);
});
// 3. Retries: a 503 is sent 1 + 2 times, a 404 only once because `setRetryOnError` skips client errors.
for (const code of [503, 404]) {
let attempts = 0;
const response = await getStatus.setParams({ status: code }).send({
onRequestStart: () => {
attempts += 1;
log(`GET /http/${code}, attempt ${attempts}`);
},
});
log(` -> ${response.status} "${response.error?.message}" after ${attempts} attempt(s)`);
}
npx tiged BetterTyped/hyper-fetch/examples/node/server hyper-fetch-node-server && cd hyper-fetch-node-server && npm install && npm run dev- Server mode: outside the browser the client caches nothing unless a request sets a scope, so data of one user never leaks to another.
- Typed
send(): responses, endpoint params and query params are typed, andsend()resolves withdataorerrorinstead of throwing. - Parallel requests with
Promise.all, one request per user. - Conditional retries:
setRetryOnErrorretries a503and gives up on a404right away.
What the terminal shows
HyperFetch on node v22.x, client mode: server
229ms GET /users -> 200, Emily Johnson, Michael Williams, Sophia Brown
229ms Fetching the posts of 3 users in parallel
307ms Emily: 1 posts, "The trees, therefore, must be such old"
307ms Michael: 2 posts, "The bustling marketplace", "The bustling city street was a feast for the senses"
307ms Sophia: 0 posts, none
307ms GET /http/503, attempt 1
691ms GET /http/503, attempt 2
1048ms GET /http/503, attempt 3
1091ms -> 503 "Service Unavailable" after 3 attempt(s)
1091ms GET /http/404, attempt 1
1126ms -> 404 "Not Found" after 1 attempt(s)
The three post requests finish at the same moment because they ran at the same time. The 503 is sent three times, 300
ms apart, and the 404 once.
How it works
-
src/api.tscreates the client withmode: "server". The default"auto"already picks it outside the browser; writing it out documents the cache rule: nothing is cached unless the request callssetScope(sessionId). -
getUsersandgetUserPostsdeclare the response and the query params in the generics.getUserPostshas a:userIdendpoint param, sosetParams({ userId })is required before sending. -
src/index.tsuses top-levelawait.getUsers.send()returns{ data, error, status }. The script checksdata, and TypeScript narrows it to the response type. -
The posts are fetched with
Promise.all(users.map(...)). Each call builds its own request withsetParams(), and all of them are in flight together. -
getStatussetssetRetry(2),setRetryTime(300)and asetRetryOnErrorcallback:.setRetryOnError((response) => response.status === null || Number(response.status) >= 500);The
onRequestStartcallback ofsend()runs for every attempt, which is how the script counts them. -
npm run buildcompiles todistwithtscandnpm startruns it with plainnode.
Bun, Deno and Workers
@hyper-fetch/core uses the standard fetch, AbortController and timers, so the same code runs on other runtimes:
- Bun:
bun src/index.ts. Bun runs TypeScript without a build step. - Deno: import the package as
npm:@hyper-fetch/core, or let Deno 2 readpackage.json, and import local files by their.tsname. Run with--allow-net. - Cloudflare Workers and other edge runtimes: create the client at module level and call
send()inside thefetchhandler. Without a top-level script, usesetScope()for anything you want cached per request.
- Backend services, cron jobs, CLIs and scripts that call other APIs.
- Server-side rendering, where the same requests the UI uses run on the server first.
- Workers that need retries, timeouts and typed responses without a framework.
Related
HyperFetch runs on the server with the same requests as in the browser. Server mode keeps the cache safe by default,
send() gives typed results without throwing, and retries are configured on the request.
