25 KiB
HTTP lib (packages/libs/src/http)
The only way code talks to the network. One HttpClient class handles requests (GET, POST, PUT, PATCH, DELETE), file upload and download, request and response interceptors, retry, automatic refresh on 401, abort, and one normalized HttpError.
It is framework-agnostic (no React, Next.js, TanStack, i18next, sonner, or zustand imports), runs in the browser and on the server, and is built on native fetch, AbortController, AbortSignal.any, AbortSignal.timeout, and XMLHttpRequest (uploads only). No axios, ky, or other dependency.
Contents: Structure · Types · API · Root and feature clients · Request pipeline · Body and params · Interceptors · Retry · Refresh token · Abort · Files · Errors · Server side · Usage · Acceptance checklist
Structure
packages/libs/src/http/
├── http-client.ts # HttpClient: config, verbs, request pipeline, extend, abortAll
├── http.ts # the root `http` instance and the createHttpClient factory
├── http-error.ts # HttpError, isHttpError, and normalization of anything thrown or returned
├── interceptors.ts # InterceptorManager; use() returns an eject function
├── retry.ts # shouldRetry, backoff with jitter and Retry-After
├── refresh.ts # single-flight refresh coordinator
├── body.ts # body and query serialization, response parsing
├── upload.ts # XMLHttpRequest transport with upload progress
├── server-http.ts # configureServerHttp; exported only from src/server.ts
├── types.ts
├── constants.ts # defaults, HTTP_ERROR_CODES, header names
└── index.ts
index.tsexportsHttpClient,createHttpClient,http,HttpError,isHttpError,HTTP_ERROR_CODES, and the types (HttpClientConfig,FeatureHttpConfig,RequestOptions,HttpResponse,UploadOptions,UploadProgress,DownloadResult,RetryConfig,RefreshConfig,RequestInterceptor,ResponseInterceptor,ErrorInterceptor,HttpErrorCode).server.tsexportsconfigureServerHttp.- Import by subpath:
import { http } from '@project/libs/http'andimport { configureServerHttp } from '@project/libs/server'.
Types
A sketch. The implementation may add fields but keeps these names and meanings.
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
interface HttpClientConfig {
baseUrl: string | (() => string); // a function is read on each request, so env is never read at module load
headers?: Record<string, string>;
timeout?: number | false; // ms per attempt, default 15_000
credentials?: RequestCredentials; // default 'include' (auth is cookie-based)
retry?: RetryConfig | false; // default: enabled with the defaults below
refresh?: RefreshConfig | false; // default: false until bootstrap sets it
getCookieHeader?: () => string | Promise<string>; // server only, set through configureServerHttp
mapErrorBody?: (body: unknown, response: Response) => Partial<HttpErrorShape>; // adapts the back end's error contract
}
interface RetryConfig {
attempts: number; // retries after the first try, default 2 (3 tries at most)
methods: HttpMethod[]; // default ['GET', 'HEAD', 'OPTIONS']
statuses: number[]; // default [408, 429, 502, 503, 504]
networkErrors: boolean; // default true (no response)
baseDelay: number; // default 300 ms
maxDelay: number; // default 5_000 ms
}
interface RefreshConfig {
endpoint: string; // relative to baseUrl or absolute, e.g. '/auth/refresh'
method?: 'POST' | 'GET'; // default 'POST'
shouldRefresh?: (error: HttpError) => boolean; // default: error.status === 401
onFailure?: () => void; // called once per failed refresh, e.g. emit the logout event
}
// What a feature may set in http.extend(). Auth settings are left out, so a feature cannot break them.
type FeatureHttpConfig = Omit<Partial<HttpClientConfig>, 'refresh' | 'credentials' | 'getCookieHeader' | 'retry'> & {
retry?: Partial<RetryConfig> | false; // merged field by field over the root's retry
};
interface RequestOptions {
params?: Record<string, QueryValue | QueryValue[] | null | undefined>;
headers?: Record<string, string>;
signal?: AbortSignal;
timeout?: number | false;
retry?: Partial<RetryConfig> | boolean; // false disables; true or an object opts in (see Retry)
skipRefresh?: boolean; // this request never triggers a refresh
responseType?: 'auto' | 'json' | 'text' | 'blob' | 'arrayBuffer'; // default 'auto'
init?: Omit<RequestInit, 'body' | 'method' | 'headers' | 'signal'>; // passthrough, e.g. keepalive or priority; never Next.js caching options
}
interface HttpResponse<T> {
data: T;
status: number;
headers: Headers;
requestId: string;
}
interface HttpErrorShape {
code: HttpErrorCode | string; // the server's code wins when the body has one
message: string;
status: number; // 0 when there was no response (network, timeout, abort)
fieldErrors?: Record<string, string>; // field path → message, e.g. { 'address.city': '...' }
hint?: string; // how the user can fix it
requestId?: string;
retryAfter?: number; // seconds, from Retry-After on 429 and 503
}
API
- Verbs resolve with the parsed body, typed by the caller (the repository passes its
*ResponseDto):get<T>(url, options?),delete<T>(url, options?),post<T>(url, body?, options?),put<T>(url, body?, options?),patch<T>(url, body?, options?). request<T>({ method, url, body, ...options })resolves withHttpResponse<T>, for when the caller needs the status, headers, or request id (pagination headers, HEAD requests).upload<T>(url, input, options?)anddownload(url, options?): see Files.interceptors.request.use(fn)andinterceptors.response.use(onSuccess?, onError?)both return an eject function.configure(partial): root client only, at bootstrap (for example to setbaseUrlandrefresh). Never after the app has started.extend(config: FeatureHttpConfig): returns a feature client. It reads the root's config live (settings made later in bootstrap still apply), runs the root's interceptors before its own, and shares the root's refresh coordinator and abort-all controller.abortAll(reason?): browser only. On the root it aborts every in-flight request of every feature (logout); on a feature client, only that feature's requests (leaving its page). New requests work right after.
Root and feature clients
- Root:
httpis created once inhttp.tswith retry on with defaults and refresh off. The app's bootstrap sets itsbaseUrlfrom the app's env (libs never read env, see lib-env.md), turns on refresh, and registers the shared interceptors. Bootstraps are idempotent, so each interceptor is registered once. A request sent beforebaseUrlis set throws a clear error instead of calling a relative URL. - Feature: every feature has
features/<feature>/http.tsexporting one client made withhttp.extend(...)and named after the feature (catalogHttp,ordersHttp). A feature with nothing special still has one:export const ordersHttp = http.extend({});. That keeps one shape everywhere, and moving a feature to its own service is a one-line change. - Only the feature's repositories import its client (
../../httpfrom a repository folder). The feature'sindex.tsdoes not export it. - The root
httpis imported only by featurehttp.tsfiles, the app's bootstrap (configure and shared interceptors), and the logout action (abortAll). Repositories never use the root client directly.
What a feature may set:
| Setting | Example | Merge |
|---|---|---|
baseUrl |
Its own service: () => getEnv().catalogApiUrl |
Replaces the root's |
headers |
An API version header only this service needs | By key; the feature wins |
timeout |
Reports and exports that need 60 s | Replaces the root's |
retry |
Search retries more; payments use retry: false |
Field by field |
| Feature-only interceptors | Unwrapping an envelope only this service uses | Run after the root's |
mapErrorBody |
Only for a back end with a different error contract | Replaces the root's |
A feature never sets refresh, credentials, or getCookieHeader: auth works the same for the whole app, and all clients share one refresh, so two features never refresh at once.
- One-off needs of a single endpoint (a longer timeout, no retry,
skipRefresh) go in that request's options, not in the feature config. - Merge order per request: lib defaults → root config → feature config → request options. Headers and retry merge by key; everything else is replaced by the more specific value.
createHttpClient(config)makes an independent client that inherits nothing. Use it only for third-party APIs that don't use the app's auth (a maps provider), in the feature'shttp.ts, withrefresh: false.
Request pipeline
- Merge the config (lib defaults → root → feature → request options). Generate one request id with
crypto.randomUUID(), kept across retries and the refresh replay, and send it asX-Request-Id. - Run request interceptors in registration order, root first. They run again on every attempt, so retries and the replay after a refresh get fresh headers.
- Serialize the body and query params. On the server, add the
Cookieheader fromgetCookieHeader(). - Send with one signal combined by
AbortSignal.anyfrom the caller'ssignal, the per-attempt timeout, the feature client's abort-all controller, and the root's. - A non-2xx status or no response is normalized to
HttpError. - If refresh applies, refresh and replay once. The replay doesn't count as a retry attempt.
- If retry applies, wait and go back to step 2.
- On success, parse the body, run the
onSuccessinterceptors, and resolve. On failure, run theonErrorinterceptors and throw the finalHttpError.
Body and params
- A plain object or array is sent as
JSON.stringifywithContent-Type: application/json. FormDatais sent as is, andContent-Typeis never set, so the platform adds the multipart boundary.URLSearchParams,Blob,File,ArrayBuffer, and strings are sent as is.undefinedsends no body. GET, HEAD, and DELETE bodies are not supported.- Query params drop
undefinedandnull, repeat the key for arrays (?tag=a&tag=b), encode withURLSearchParams, and merge with any query string already in the URL. responseType: 'auto': 204, 205, or an empty body resolves withundefined; a JSON content type is parsed; anything else resolves as text. Invalid JSON throwsPARSE_ERROR.- Unwrapping a back-end envelope (
{ data, meta }) is a response interceptor's job: on the root when every service uses it, on the feature client when only that service does. Never in each repository.
Interceptors
- Request:
(config: RequestConfig) => RequestConfig | Promise<RequestConfig>. Return a new config; never mutate the argument. - Response:
onSuccess(response: HttpResponse<unknown>)returns a response, andonError(error: HttpError)returns anHttpError.onErrormay change the error but can't turn a failure into a success, so a resolved promise always means success. - Both run in registration order, root before feature. A throwing interceptor fails the request with
INTERCEPTOR_ERROR. - Use them for cross-cutting concerns:
Accept-Languagefrom the current locale, envelope unwrapping, dev logging, Sentry breadcrumbs (method, URL, status, request id). - Never put business logic, toasts, navigation, store writes, or per-user module state in them (on the server one client serves every user), and never log cookies or auth headers.
- Shared interceptors are registered on the root in bootstrap; feature-only interceptors in the feature's
http.ts, right afterextend. Never in components, models, or repositories.
Retry
- An attempt is retried when its method is in
retry.methods, the failure is a network error or a status inretry.statuses, attempts are left, and the request wasn't aborted. - The default methods are idempotent reads. POST and PATCH are never retried by default; a request may opt in with
retry: trueonly when it sends an idempotency key the back end honors. - Delay: exponential backoff with full jitter,
random(0, min(maxDelay, baseDelay * 2 ** attempt)). When the response hasRetry-After(seconds or a date), wait that long instead, capped atmaxDelay. Aborting during the wait rejects at once withABORTED. - Never retried: 4xx other than 408 and 429,
ABORTED,TIMEOUTon non-idempotent methods, and uploads (the UI offers a retry button). - On the server the defaults are
attempts: 1and a shorter timeout (about 5 s), so one slow back end doesn't hold up rendering; the page streams around it. - TanStack Query must not retry on top:
configs/react-query.tssets queries'retry: false, and the user retries from the error fallback or the toast (error-handling.md). Otherwise one failure multiplies into attempts × query retries.
Refresh token
- Auth is cookie-based: the refresh endpoint reads the refresh cookie and the server sets new cookies. The lib never reads or stores tokens.
- Trigger:
shouldRefresh(error)is true (default: 401), refresh is configured, the request didn't setskipRefresh, it isn't the refresh request itself, and it hasn't already been replayed after a refresh. - Single flight: one refresh at a time for the whole app, because the root and every feature client share one coordinator. Requests that get a 401 while a refresh runs wait for it.
- Stale 401: each successful refresh increments a generation number. A request sent before the latest successful refresh that returns 401 is replayed right away, without another refresh.
- On success, every waiting request is replayed once. A replay that gets 401 again fails with
UNAUTHORIZEDwithout refreshing again, so there are no loops. - On failure, every waiting request fails with
UNAUTHORIZEDandonFailure()runs once (the app emits its logout event; the auth feature clears the store, and on a page that needs a logged-in user theAuthGuardsends the user to login). Later requests try normally, so logging in again works without a reload. - The refresh request is sent with
skipRefresh: true,retry: false, and the normal timeout, and runs request interceptors like any request. - Waiting is abortable per request: an aborted waiter rejects with
ABORTEDwhile the refresh continues for the others. - In the browser, run the refresh inside
navigator.locks.request('http-refresh', ...)when available, so two tabs never send the same refresh cookie at once (the back end may rotate and revoke it). - On the server refresh is disabled. Server requests send no auth cookies (Server side), so the server render never reads or refreshes the session, and a 401 there throws
UNAUTHORIZEDto its boundary.
Abort
- Per request: pass
signal. Repositories take an optional last parameter{ signal?: AbortSignal }and forward it, soqueryFn: ({ signal }) => productsRepository.list(args, { signal })cancels stale requests on unmount or key change. - Timeout: per attempt, from
timeout(request option → feature → root → default).timeout: falsedisables it. Uploads and downloads default to no timeout; the user cancels them instead. - Whole app:
http.abortAll()in the logout action, so no request from the old session finishes after logout. One feature:catalogHttp.abortAll(), for example when leaving a page with long-running requests. - Never call
abortAllon the server: clients are shared by every user's requests. - The caller's or abort-all's signal produces
ABORTED; the timeout producesTIMEOUT. Tell them apart by which signal fired, not by the message. - Aborted requests are never retried, never trigger a refresh, and never call
onFailure. The UI ignoresABORTEDerrors: no toast, no error state.
Files
upload<T>(url: string, input: File | Blob | File[] | FormData, options?: UploadOptions): Promise<T>;
interface UploadOptions extends Omit<RequestOptions, 'responseType'> {
method?: 'POST' | 'PUT' | 'PATCH'; // default 'POST'
fieldName?: string; // default 'file', used when input is a File, Blob, or File[]
fields?: Record<string, string>; // extra form fields sent with the file
onProgress?: (progress: UploadProgress) => void;
}
interface UploadProgress {
loaded: number;
total: number;
percent: number; // integer 0–100
}
download(url: string, options?: DownloadOptions): Promise<DownloadResult>;
interface DownloadOptions extends Omit<RequestOptions, 'responseType'> {
onProgress?: (progress: UploadProgress) => void;
}
interface DownloadResult {
blob: Blob;
fileName?: string;
contentType?: string;
}
uploadwraps a File, Blob, or File[] inFormDataunderfieldName(repeated for arrays) withfields. It usesXMLHttpRequest, becausefetchcan't report upload progress, and still runs interceptors, sends cookies (withCredentials), uses the request id, normalizes errors, and joins the refresh flow (the file is re-sent after a successful refresh).signalcallsxhr.abort(). No automatic retry.- The UI shows the percentage, file name and size, and a cancel button wired to the signal (see b2c-b2b.md).
downloadusesfetch.fileNamecomes fromContent-Disposition(filename*first, thenfilename). Progress is reported while reading the body stream whenContent-Lengthis known. Saving the blob (object URL and link click) is a small browser util inshared/utils, not in the lib.post(url, formData)is fine for a small file when the UI needs no progress or cancel.
Errors
- Every failure from every step is thrown as one
HttpError: it extendsErrorand has theHttpErrorShapefields plusmethod,url, andcause. The lib throws nothing else. isHttpError(error)checks a brand such asSymbol.for('project.http-error'), not onlyinstanceof, because server and client bundles can hold separate copies of the class.toJSON()returns the plain shape for logs and Sentry.mapErrorBodyreads the error body (default:code,message,hint, andfieldErrorsorerrorsfrom a JSON body). Set it once on the root when the back-end contract differs; a feature sets its own only for a back end with a different contract.requestIdis the server'sX-Request-Idresponse header when present, otherwise the id the client sent, so even network errors can be traced.retryAfteris theRetry-Afterheader of a 429 or 503 in seconds (a date is converted), so the UI can say how long to wait.- Server messages pass through as is; the back end localizes them from
Accept-Language. Messages the lib creates (network, timeout, parse, unknown) are i18n keys such aserrors:http.network, with a matching hint key, and the UI translates them. The lib never imports i18next. - The lib never shows errors. The error handler lib decides what each one shows and reports it (lib-error-handler.md): a failed read reaches its error boundary or an empty state, a failed action goes through
applyServerErrorsorshowActionError(fields, form alert, toast), and the auth feature handles logout (error-handling.md).
| Code | When |
|---|---|
NETWORK_ERROR |
No response |
TIMEOUT |
The per-attempt timeout fired |
ABORTED |
The caller or abortAll aborted it |
VALIDATION |
400 or 422 with field errors |
BAD_REQUEST |
Other 400 |
UNAUTHORIZED |
401 |
FORBIDDEN |
403 |
NOT_FOUND |
404 |
CONFLICT |
409 |
RATE_LIMITED |
429 |
SERVER_ERROR |
5xx |
PARSE_ERROR |
The body couldn't be parsed |
INTERCEPTOR_ERROR |
An interceptor threw |
UNKNOWN |
Anything else |
Server side
bootstrap.server.tscallsconfigureServerHttponce (code below). It sets the root's serverbaseUrl(from the app's server env, for example an internal service address) and the cookie provider on the root, so every feature client forwards the same cookies. A feature with its ownbaseUrlreads it through its project'sgetEnv(), which the server bootstrap fills with the server-side address.getCookieHeaderruns on every server request and forwards only the names in the app'sFORWARDED_COOKIES, the cookies the server render needs, such asLOCALE_COOKIEandTHEME_COOKIE. It never forwards the auth cookies, so no back-end response on the server depends on who the viewer is (rendering-patterns.md). Never keep cookies, users, or tokens in module state.- On the server, refresh is off,
abortAllis unavailable, retry defaults to one attempt with a shorter timeout,credentialsis ignored, and every request is sent withcache: 'no-store', whateverinitsays. initnever carries Next.js caching options (next: { revalidate, tags }): the Next.js server keeps no cache between requests (see b2c-b2b.md).
bootstrap.server.ts:
configureServerHttp({
baseUrl: serverEnv.API_INTERNAL_URL,
getCookieHeader: async () =>
(await cookies())
.getAll()
.filter(({ name }) => FORWARDED_COOKIES.has(name))
.map(({ name, value }) => `${name}=${encodeURIComponent(value)}`)
.join('; '),
});
FORWARDED_COOKIES is a ReadonlySet<string> in the app's constants/, built from the cookie name constants (lib-cookie.md). Adding an auth cookie to it is an override of rendering-patterns.md's Auth-dependent UI rule and needs a recorded decision.
Usage
features/catalog/http.ts. getEnv is the owning project's env getter (see lib-env.md).
import { http } from '@project/libs/http';
import { getEnv } from '../../env';
export const catalogHttp = http.extend({
baseUrl: () => getEnv().catalogApiUrl,
timeout: 30_000,
retry: { attempts: 3 },
});
catalogHttp.interceptors.response.use((response) => ({
...response,
data: (response.data as CatalogEnvelope).result,
}));
features/orders/http.ts, a feature with nothing special:
import { http } from '@project/libs/http';
export const ordersHttp = http.extend({});
features/catalog/repositories/products/products.ts
import type { DownloadResult, UploadProgress } from '@project/libs/http';
import { catalogHttp } from '../../http';
export const productsRepository = {
async list(args: ListProductsArgs, options?: { signal?: AbortSignal }): Promise<ListProductsPayload> {
const response = await catalogHttp.get<ListProductsResponseDto>(PRODUCTS_ENDPOINT, {
params: toListProductsParams(args),
signal: options?.signal,
});
return toListProductsPayload(response);
},
async uploadImage(
args: UploadProductImageArgs,
options?: { signal?: AbortSignal; onProgress?: (progress: UploadProgress) => void },
): Promise<ProductImagePayload> {
const response = await catalogHttp.upload<UploadImageResponseDto>(
productImageEndpoint(args.productId),
args.file,
options,
);
return toProductImagePayload(response);
},
exportReport(args: ExportProductsArgs): Promise<DownloadResult> {
return catalogHttp.download(PRODUCTS_EXPORT_ENDPOINT, { params: toExportParams(args), timeout: 120_000 });
},
};
The export's long timeout applies to that one request, so it is a request option, not feature config.
Bootstrap, root client only (bootstrap.client.ts). The refresh endpoint and logout event come from the auth feature's public API.
http.configure({
baseUrl: clientEnv.NEXT_PUBLIC_API_URL,
refresh: { endpoint: AUTH_ENDPOINTS.refresh, onFailure: () => eventEmitter.emit(AUTH_EVENTS.logout) },
});
http.interceptors.request.use((config) => ({
...config,
headers: { ...config.headers, 'Accept-Language': i18n.language },
}));
Acceptance checklist
For building or changing the lib:
[ ] GET, POST, PUT, PATCH, DELETE send the right method, headers, JSON or FormData body, and query params, and resolve with the parsed body
[ ] A request sent before bootstrap sets the root's baseUrl throws a clear "not configured" error
[ ] 204 resolves with undefined; invalid JSON throws PARSE_ERROR
[ ] Request and response interceptors run in order, re-run on retry and replay, and eject works
[ ] A GET that gets 503 twice then 200 resolves after 3 tries; a POST that gets 503 fails at once
[ ] Retry-After is respected; aborting during the backoff wait rejects at once with ABORTED
[ ] Five parallel requests that all get 401 cause exactly one refresh, then all five replay and resolve, also across feature clients
[ ] http.extend rejects refresh, credentials, and getCookieHeader at type level; feature headers and retry merge over the root's; request options win over both
[ ] A feature client runs the root's interceptors before its own and sees root settings made after it was created
[ ] A failed refresh rejects all waiters with UNAUTHORIZED and calls onFailure exactly once
[ ] A replay that gets 401 again fails without a second refresh
[ ] Caller abort gives ABORTED and timeout gives TIMEOUT; http.abortAll() aborts every feature's requests, a feature's abortAll() only its own, and new requests still work
[ ] Upload reports progress from 0 to 100, can be cancelled, and joins the refresh flow
[ ] Download returns the blob and the file name from Content-Disposition
[ ] Every failure is an HttpError with code, message, status, fieldErrors, hint, and requestId, plus retryAfter on a 429 or 503 that sends Retry-After; isHttpError works across bundles
[ ] On the server, each request forwards only its own allowed cookies and never the auth cookies, is sent with cache: 'no-store', refresh never runs, and no state leaks between requests