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
- 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 with `HttpResponse<T>`, for when the caller needs the status, headers, or request id (pagination headers, HEAD requests).
-`upload<T>(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:** `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/<feature>/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<RequestConfig>`. Return a new config; never mutate the argument.
- Response: `onSuccess(response: HttpResponse<unknown>)` 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.
- 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 redirects). 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 Components can't set cookies, so a 401 throws `UNAUTHORIZED`, and `proxy.ts` refreshes an expired session before rendering.
- 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.
-`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.
-`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.
- 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)).
-`bootstrap.server.ts` calls `configureServerHttp({ baseUrl: serverEnv.API_INTERNAL_URL, getCookieHeader: async () => (await cookies()).toString() })` once. 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 cookies too. 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, so each request forwards its own user's cookies. 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)).
[ ] 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