# 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.ts` exports `HttpClient`, `createHttpClient`, `http`, `HttpError`, `isHttpError`, `HTTP_ERROR_CODES`, and the types (`HttpClientConfig`, `FeatureHttpConfig`, `RequestOptions`, `HttpResponse`, `UploadOptions`, `UploadProgress`, `DownloadResult`, `RetryConfig`, `RefreshConfig`, `RequestInterceptor`, `ResponseInterceptor`, `ErrorInterceptor`, `HttpErrorCode`). - `server.ts` exports `configureServerHttp`. - Import by subpath: `import { http } from '@project/libs/http'` and `import { configureServerHttp } from '@project/libs/server'`. ## Types A sketch. The implementation may add fields but keeps these names and meanings. ```ts 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; 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; // server only, set through configureServerHttp mapErrorBody?: (body: unknown, response: Response) => Partial; // 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, 'refresh' | 'credentials' | 'getCookieHeader' | 'retry'> & { retry?: Partial | false; // merged field by field over the root's retry }; interface RequestOptions { params?: Record; headers?: Record; signal?: AbortSignal; timeout?: number | false; retry?: Partial | 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; // passthrough, e.g. keepalive or priority; never Next.js caching options } interface HttpResponse { 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; // 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(url, options?)`, `delete(url, options?)`, `post(url, body?, options?)`, `put(url, body?, options?)`, `patch(url, body?, options?)`. - `request({ method, url, body, ...options })` resolves with `HttpResponse`, for when the caller needs the status, headers, or request id (pagination headers, HEAD requests). - `upload(url, input, options?)` and `download(url, options?)`: see Files. - `interceptors.request.use(fn)` and `interceptors.response.use(onSuccess?, onError?)` both return an eject function. - `configure(partial)`: root client only, at bootstrap (for example to set `baseUrl` and `refresh`). 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:** `http` is created once in `http.ts` with retry on with defaults and refresh off. The app's bootstrap sets its `baseUrl` from the app's env (libs never read env, see [lib-env.md](lib-env.md)), turns on refresh, and registers the shared interceptors. Bootstraps are idempotent, so each interceptor is registered once. A request sent before `baseUrl` is set throws a clear error instead of calling a relative URL. - **Feature:** every feature has `features//http.ts` exporting one client made with `http.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 (`../../http` from a repository folder). The feature's `index.ts` does not export it. - The root `http` is imported only by feature `http.ts` files, 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's `http.ts`, with `refresh: false`. ## Request pipeline 1. 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 as `X-Request-Id`. 2. 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. 3. Serialize the body and query params. On the server, add the `Cookie` header from `getCookieHeader()`. 4. Send with one signal combined by `AbortSignal.any` from the caller's `signal`, the per-attempt timeout, the feature client's abort-all controller, and the root's. 5. A non-2xx status or no response is normalized to `HttpError`. 6. If refresh applies, refresh and replay once. The replay doesn't count as a retry attempt. 7. If retry applies, wait and go back to step 2. 8. On success, parse the body, run the `onSuccess` interceptors, and resolve. On failure, run the `onError` interceptors and throw the final `HttpError`. ## Body and params - A plain object or array is sent as `JSON.stringify` with `Content-Type: application/json`. - `FormData` is sent as is, and `Content-Type` is never set, so the platform adds the multipart boundary. - `URLSearchParams`, `Blob`, `File`, `ArrayBuffer`, and strings are sent as is. `undefined` sends no body. GET, HEAD, and DELETE bodies are not supported. - Query params drop `undefined` and `null`, repeat the key for arrays (`?tag=a&tag=b`), encode with `URLSearchParams`, and merge with any query string already in the URL. - `responseType: 'auto'`: 204, 205, or an empty body resolves with `undefined`; a JSON content type is parsed; anything else resolves as text. Invalid JSON throws `PARSE_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`. Return a new config; never mutate the argument. - Response: `onSuccess(response: HttpResponse)` returns a response, and `onError(error: HttpError)` returns an `HttpError`. `onError` may 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-Language` from 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 after `extend`. 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 in `retry.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: true` only 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 has `Retry-After` (seconds or a date), wait that long instead, capped at `maxDelay`. Aborting during the wait rejects at once with `ABORTED`. - Never retried: 4xx other than 408 and 429, `ABORTED`, `TIMEOUT` on non-idempotent methods, and uploads (the UI offers a retry button). - On the server the defaults are `attempts: 1` and 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.ts` sets queries' `retry: false`, and the user retries from the error fallback or the toast ([error-handling.md](error-handling.md#reads)). 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 set `skipRefresh`, 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 `UNAUTHORIZED` without refreshing again, so there are no loops. - On failure, every waiting request fails with `UNAUTHORIZED` and `onFailure()` runs once (the app emits its logout event; the auth feature clears the store, and on a page that needs a logged-in user the `AuthGuard` sends 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 `ABORTED` while 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 `UNAUTHORIZED` to its boundary. ## Abort - Per request: pass `signal`. Repositories take an optional last parameter `{ signal?: AbortSignal }` and forward it, so `queryFn: ({ signal }) => productsRepository.list(args, { signal })` cancels stale requests on unmount or key change. - Timeout: per attempt, from `timeout` (request option → feature → root → default). `timeout: false` disables 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 `abortAll` on the server: clients are shared by every user's requests. - The caller's or abort-all's signal produces `ABORTED`; the timeout produces `TIMEOUT`. 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 ignores `ABORTED` errors: no toast, no error state. ## Files ```ts upload(url: string, input: File | Blob | File[] | FormData, options?: UploadOptions): Promise; interface UploadOptions extends Omit { method?: 'POST' | 'PUT' | 'PATCH'; // default 'POST' fieldName?: string; // default 'file', used when input is a File, Blob, or File[] fields?: Record; // 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; interface DownloadOptions extends Omit { onProgress?: (progress: UploadProgress) => void; } interface DownloadResult { blob: Blob; fileName?: string; contentType?: string; } ``` - `upload` wraps a File, Blob, or File[] in `FormData` under `fieldName` (repeated for arrays) with `fields`. It uses `XMLHttpRequest`, because `fetch` can'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). `signal` calls `xhr.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](ui-rules.md#file-uploads)). - `download` uses `fetch`. `fileName` comes from `Content-Disposition` (`filename*` first, then `filename`). Progress is reported while reading the body stream when `Content-Length` is known. Saving the blob (object URL and link click) is a small browser util in `shared/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 extends `Error` and has the `HttpErrorShape` fields plus `method`, `url`, and `cause`. The lib throws nothing else. - `isHttpError(error)` checks a brand such as `Symbol.for('project.http-error')`, not only `instanceof`, because server and client bundles can hold separate copies of the class. - `toJSON()` returns the plain shape for logs and Sentry. - `mapErrorBody` reads the error body (default: `code`, `message`, `hint`, and `fieldErrors` or `errors` from 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. - `requestId` is the server's `X-Request-Id` response header when present, otherwise the id the client sent, so even network errors can be traced. - `retryAfter` is the `Retry-After` header 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 as `errors: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](lib-error-handler.md)): a failed read reaches its error boundary or an empty state, a failed action goes through `applyServerErrors` or `showActionError` (fields, form alert, toast), and the auth feature handles logout ([error-handling.md](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.ts` calls `configureServerHttp` once (code below). It sets the root's server `baseUrl` (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 own `baseUrl` reads it through its project's `getEnv()`, which the server bootstrap fills with the server-side address. - `getCookieHeader` runs on every server request and forwards only the names in the app's `FORWARDED_COOKIES`, the cookies the server render needs, such as `LOCALE_COOKIE` and `THEME_COOKIE`. It never forwards the auth cookies, so no back-end response on the server depends on who the viewer is ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). Never keep cookies, users, or tokens in module state. - On the server, refresh is off, `abortAll` is unavailable, retry defaults to one attempt with a shorter timeout, `credentials` is ignored, and every request is sent with `cache: 'no-store'`, whatever `init` says. - `init` never carries Next.js caching options (`next: { revalidate, tags }`): the Next.js server keeps no cache between requests (see [b2c-b2b.md](b2c-b2b.md#no-server-cache)). `bootstrap.server.ts`: ```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` in the app's `constants/`, built from the cookie name constants ([lib-cookie.md](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](lib-env.md#project-env)). ```ts 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: ```ts import { http } from '@project/libs/http'; export const ordersHttp = http.extend({}); ``` `features/catalog/repositories/products/products.ts` ```ts import type { DownloadResult, UploadProgress } from '@project/libs/http'; import { catalogHttp } from '../../http'; export const productsRepository = { async list(args: ListProductsArgs, options?: { signal?: AbortSignal }): Promise { const response = await catalogHttp.get(PRODUCTS_ENDPOINT, { params: toListProductsParams(args), signal: options?.signal, }); return toListProductsPayload(response); }, async uploadImage( args: UploadProductImageArgs, options?: { signal?: AbortSignal; onProgress?: (progress: UploadProgress) => void }, ): Promise { const response = await catalogHttp.upload( productImageEndpoint(args.productId), args.file, options, ); return toProductImagePayload(response); }, exportReport(args: ExportProductsArgs): Promise { 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. ```ts 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 ```