@molecule/app-http
Core interface · http · App (browser) · v1.5.8 · Apache-2.0
HTTP client with interceptors and providers
npm install @molecule/app-httpHow it works
@molecule/app-http is the http core interface on the app (browser) side: the API your app calls, with no vendor inside.
Choose the implementation by bonding one of its 1 provider: @molecule/app-http-axios.
// In a React component, get the configured client from context and call it.
// The hook is exported by the framework binding (@molecule/app-react), not
// this core package — never construct your own fetch/axios client.
import { useHttpClient } from '@molecule/app-react'
function Plants() {
const http = useHttpClient()
const load = async () => {
const res = await http.get<Plant[]>('/plants') // the bonded client's baseURL ('/api') is prepended
setPlants(res.data)
}
// Body-carrying verbs take the body as the SECOND argument:
// http.post('/plants', plant) — wire body is `plant`
// http.post('/plants', { data: plant }) — WRONG: wire body is `{"data": plant}`
// http.put(url, body), http.patch(url, body) and http.delete(url) are also available.
}Providers (1): @molecule/app-http-axios
Works with: @molecule/app-bond, @molecule/app-i18n, @molecule/app-logger
Reference
Client HTTP interface for molecule.dev.
Provides a unified HTTP client API that works across different HTTP libraries (fetch, axios, ky, etc.).
The body is the SECOND argument: post(url, data, config?) — likewise put and patch,
and the response is HttpResponse<T> (read .data for the body). data IS the request
body; a plain object is serialized as the JSON body. Passing { data: body } there is NOT a
config object — it makes the wire body {"data":{…}}, so the API sees an object whose only
key is data, finds none of the fields it validates, and answers
422 {"errors":{"username":["can't be blank"],…}}. Write post('/users', { user }), never
post('/users', { data: { user } }). The config object (headers, params, timeout,
skipAuthGate) is the THIRD argument. Only request({ method, url, data, … }) takes data
inside an options object, because there that object IS the config.
Response helpers preserve API-specific field names. unwrapSingle<T>(response) peels
transport and data envelopes. It does not select a named resource such as { record: T }.
For that body, read unwrapSingle<{ record: RecordType }>(response)?.record, or
response.data.record with a typed client call. For a bare resource body, keep the resource
directly. The generic is a type assertion, not runtime validation of the server's schema.
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Quick Start
// In a React component, get the configured client from context and call it.
// The hook is exported by the framework binding (@molecule/app-react), not
// this core package — never construct your own fetch/axios client.
import { useHttpClient } from '@molecule/app-react'
function Plants() {
const http = useHttpClient()
const load = async () => {
const res = await http.get<Plant[]>('/plants') // the bonded client's baseURL ('/api') is prepended
setPlants(res.data)
}
// Body-carrying verbs take the body as the SECOND argument:
// http.post('/plants', plant) — wire body is `plant`
// http.post('/plants', { data: plant }) — WRONG: wire body is `{"data": plant}`
// http.put(url, body), http.patch(url, body) and http.delete(url) are also available.
}
Type
core
Installation
npm install @molecule/app-http @molecule/app-bond @molecule/app-i18n @molecule/app-logger
API
Interfaces
HttpClient
HTTP client interface.
All HTTP providers must implement this interface.
interface HttpClient {
/**
* Base URL for all requests.
*/
baseURL: string
/**
* Default headers for all requests.
*/
defaultHeaders: Record<string, string>
/**
* Makes a generic HTTP request. `data` is a field of THIS config object — the same body
* `post(url, data, config)` takes as its second argument.
*/
request<T = unknown>(config: FullRequestConfig): Promise<HttpResponse<T>>
/**
* Makes a GET request.
*/
get<T = unknown>(url: string, config?: RequestConfig): Promise<HttpResponse<T>>
/**
* Makes a POST request. `data` is the request BODY, not a config object: the wire body is
* `data` itself, so `post(url, { data: body })` sends `{"data":body}` — pass `body` directly.
* A config (headers, params) is the THIRD argument.
*/
post<T = unknown>(url: string, data?: unknown, config?: RequestConfig): Promise<HttpResponse<T>>
/**
* Makes a PUT request. `data` is the request BODY (second argument) — never `{ data: body }`,
* which sends `{"data":body}`; a config is the THIRD argument.
*/
put<T = unknown>(url: string, data?: unknown, config?: RequestConfig): Promise<HttpResponse<T>>
/**
* Makes a PATCH request. `data` is the request BODY (second argument) — never `{ data: body }`,
* which sends `{"data":body}`; a config is the THIRD argument.
*/
patch<T = unknown>(url: string, data?: unknown, config?: RequestConfig): Promise<HttpResponse<T>>
/**
* Makes a DELETE request.
*/
delete<T = unknown>(url: string, config?: RequestConfig): Promise<HttpResponse<T>>
/**
* Adds a request interceptor.
* Returns a function to remove the interceptor.
*/
addRequestInterceptor(interceptor: RequestInterceptor): () => void
/**
* Adds a response interceptor.
* Returns a function to remove the interceptor.
*/
addResponseInterceptor(interceptor: ResponseInterceptor): () => void
/**
* Adds an error interceptor.
* Returns a function to remove the interceptor.
*/
addErrorInterceptor(interceptor: ErrorInterceptor): () => void
/**
* Sets the authorization token.
*
* A static token: every request carries it until the next `setAuthToken` call. A client
* that has a `resolver` (registered through
* `@molecule/app-http`'s `setAuthTokenSource`) ignores this value when it assembles a
* request — the resolver IS the session, and reading it per request is what keeps a
* session adopted without an auth event from sending the previous account's bearer. Once
* the resolver is removed, the static token is sent again.
*/
setAuthToken(token: string | null): void
/**
* Returns the token the client applies to its next request: the resolver's answer when one
* is registered, else the static token from `setAuthToken`.
*/
getAuthToken(): string | null
/**
* Registers the LIVE token resolver every request of this client reads, or clears it with
* `null`.
*
* `@molecule/app-http`'s `setAuthTokenSource()` calls this on every client it bonds, and the
* client MUST consult the resolver again each time it assembles a request (and report it from
* `getAuthToken()`). A session can change with no auth event and no observable state change —
* `authClient.setSession()` with the same profile data, or the OAuth callback's
* `setAccessToken()` — so a token pushed only at bond time or on `login`/`logout` events
* leaves every later request carrying the PREVIOUS session's bearer while the UI shows the
* new one.
*
* The resolved token takes the static token's place, with the same precedence: an
* `Authorization` header passed per request or in the client's default headers wins over it
* exactly where it won over a static token in this transport.
*
* A resolver that returns `null` (or `undefined`) means "this session has no body token": the
* request carries no `Authorization` header of the client's own. A cookie-session API issues
* no bearer, and the server prefers the header over the fresh cookie, so a kept bearer
* authenticates as the prior — possibly deleted — session.
*
* Optional, so an implementation written against the previous interface still conforms.
* `setAuthTokenSource()` follows such a client through a request interceptor instead, pushing
* the source with `setAuthToken` before each request: that request carries the change only
* when the transport applies its token after running its interceptors, so a transport that
* applies it earlier sends a session adopted mid-page from the following request on.
*
* @param resolver - Returns the current access token (or null/undefined), or `null` to clear.
*/
setAuthTokenResolver?(resolver: AuthTokenResolver | null): void
/**
* Registers a handler for authentication errors (401).
*
* @returns An unsubscribe function.
*/
onAuthError(handler: () => void): () => void
}
HttpClientConfig
HTTP client configuration.
interface HttpClientConfig {
/**
* Base URL for all requests: a path (`/api`) or an absolute URL
* (`https://api.example.com/api`). A request path that already starts with the base's
* path (`/api/users`) is not prefixed again, and a URL with its own host (`https://…`,
* `//cdn…`) is requested as written.
*/
baseURL?: string
/**
* Default headers for all requests.
*/
defaultHeaders?: Record<string, string>
/**
* Default timeout in milliseconds.
*/
timeout?: number
/**
* Whether to include credentials by default.
*/
withCredentials?: boolean
/**
* The scheme of the `Authorization` header the auth token is sent with:
* `Bearer` (default), or what your API expects, e.g. `Token` for an API that
* reads `Authorization: Token <jwt>`. It is an option of the client's
* CONSTRUCTOR (`createFetchClient({ baseURL, authScheme: 'Token' })`, or the
* bonded provider's `createAxiosClient({ … })`), never a property of the client
* it returns.
*/
authScheme?: string
/**
* Default retry policy for every request this client makes, or `false` to
* disable retries. A request's own `retry` overrides it.
*/
retry?: RetryOptions | false
}
RetryOptions
Tuning for the retry policy.
interface RetryOptions {
/**
* Maximum retries AFTER the first attempt. Defaults to `2` (three attempts
* in total).
*/
maxRetries?: number
/** Base backoff in milliseconds. Defaults to `300`. */
baseDelayMs?: number
/** Maximum backoff (before `Retry-After` can extend it). Defaults to `5000`. */
maxDelayMs?: number
/** Statuses treated as transient. Defaults to `[502, 503, 504]`. */
retryStatuses?: number[]
}
RetryDecisionInput
The request fields the policy decides from.
interface RetryDecisionInput {
/** The request method. */
method: HttpMethod
/** The request headers (lower-cased lookup is done here). */
headers: Record<string, string | undefined>
/** The HTTP status, or `0` when no response arrived. */
status: number
/** How many retries have already been made (0 for the first failure). */
attempt: number
/** The error message, used to recognize a connection reset/refusal. */
errorMessage?: string
/** `true` when the request was aborted before a response. */
aborted?: boolean
/** Overrides layered over `DEFAULT_RETRY_OPTIONS`. */
options?: RetryOptions | false
}
RequestConfig
HTTP request options (headers, query params, timeout, credentials, response type, abort signal).
interface RequestConfig {
/**
* Request headers.
*/
headers?: Record<string, string>
/**
* Query parameters.
*/
params?: Record<string, string | number | boolean | undefined>
/**
* Request timeout in milliseconds.
*/
timeout?: number
/**
* Whether to include credentials (cookies).
*/
withCredentials?: boolean
/**
* Send this request WITHOUT waiting for the session restore (the auth gate).
*
* A request the gate's restore issues from a LATER continuation must set this. The gate
* recognizes a request the settle function issues while it runs and never holds it — this
* package's client awaits the gate before anything else, so a `restoreSession()` that calls
* it directly does not deadlock. But a restore that awaits something else first
* (`await storage.get()`), then calls the client, reaches `awaitAuthGate` after that window:
* the gate then waits on itself, and every request on the page stalls until the gate times
* out (3 s) — so pass `skipAuthGate: true` on that request. A provider that awaits the gate
* inside a scheduled interceptor (the Axios bond) also reaches it after the window, so its
* restore's request needs the opt-out.
*
* ```typescript
* // the request the gate's restore makes, through the same client the gate holds back
* await http.get(currentUserEndpoint, { skipAuthGate: true })
* ```
*
* `@molecule/app-auth`'s own restore does not need it — it sends its request with
* `fetch`, not through this client. An app with its own session store that registers a
* gate with `setAuthGate` does not need it either when its restore calls the client
* directly.
*/
skipAuthGate?: boolean
/**
* Response type.
*/
responseType?: 'json' | 'text' | 'blob' | 'arraybuffer'
/**
* Abort signal for cancellation.
*/
signal?: AbortSignal
/**
* Request body data, as a field of THIS config object — the `request({ method, url, data })`
* form. The verb methods take the body as their SECOND argument: `post(url, data, config)`,
* `put(url, data, config)`, `patch(url, data, config)`. Never wrap it there as
* `{ data: body }`: that object is the body, so the wire sends `{"data":body}` and the API
* sees none of the fields at its top level.
*/
data?: unknown
/**
* Custom request options (implementation-specific).
*/
options?: Record<string, unknown>
/**
* Retry policy for this request, or `false` to disable retries.
*
* The default policy retries only IDEMPOTENT requests (`GET`/`HEAD`/`PUT`/
* `DELETE`/`OPTIONS`, and `POST`/`PATCH` carrying an `Idempotency-Key`) on
* `502`/`503`/`504` or a reset/refused connection, twice, with exponential
* backoff and jitter, honoring `Retry-After`. See `@molecule/app-http`'s
* `shouldRetryRequest`.
*/
retry?: RetryOptions | false
}
AuthGateRequest
What the auth gate is told about the request it is about to hold: whether the request opts out of the wait, and how to name it in the stalled-gate report.
A request's own RequestConfig satisfies this — the providers pass it straight through
(awaitAuthGate(requestConfig)), so a provider never has to build one by hand.
interface AuthGateRequest {
/**
* Send this request without waiting for the gate at all — see
* `RequestConfig.skipAuthGate`.
*/
skipAuthGate?: boolean
/**
* The request's HTTP method, for the message logged when the gate never settles.
*/
method?: string
/**
* The request's URL, for the message logged when the gate never settles. Any userinfo or
* credential query/fragment values are redacted from that report; non-secret parts remain.
*/
url?: string
}
FullRequestConfig
Full request configuration including method and URL.
interface FullRequestConfig extends RequestConfig {
/**
* HTTP method.
*/
method: HttpMethod
/**
* Request URL (can be relative or absolute).
*/
url: string
/**
* Request body data — a field of this config object, never a second argument here.
*/
data?: unknown
}
HttpResponse
Parsed HTTP response with status code, headers, and typed body data.
interface HttpResponse<T = unknown> {
/**
* Response data.
*/
data: T
/**
* HTTP status code.
*/
status: number
/**
* HTTP status text.
*/
statusText: string
/**
* Response headers.
*/
headers: Record<string, string>
/**
* Original request config.
*/
config: FullRequestConfig
}
Types
AuthTokenResolver
A live access-token resolver: called once per request, it returns the token the session
holds NOW (null/undefined when the session carries no body token — a cookie-session API).
@molecule/app-http's setAuthTokenSource() installs one on every client it bonds, so the
app's auth bond decides the bearer and the client resolves it per request instead of holding
a copy that a session adopted mid-page can leave stale.
type AuthTokenResolver = () => string | null | undefined
RequestInterceptor
Intercepts outgoing requests to modify headers, URL, or body before the request is sent.
type RequestInterceptor = (
config: FullRequestConfig,
) => FullRequestConfig | Promise<FullRequestConfig>
config— The full request configuration to transform.
ResponseInterceptor
Intercepts incoming responses to transform data, check status, or perform side effects before the response reaches the caller.
type ResponseInterceptor<T = unknown> = (
response: HttpResponse<T>,
) => HttpResponse<T> | Promise<HttpResponse<T>>
ErrorInterceptor
Intercepts HTTP errors to transform, retry, or rethrow them. Throwing from this interceptor propagates the error to the caller.
type ErrorInterceptor = (error: HttpError) => HttpError | Promise<HttpError> | never
HttpMethod
HTTP request method.
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS'
Classes
HttpError
HTTP error with response details.
instanceof HttpError also recognizes compatible failures carrying the shared
Symbol.for('@molecule/app-http/HttpError') brand, including non-ok auth responses
and errors from duplicated package copies. Branded producers must provide this
class's instance fields. Subclasses retain ordinary prototype-based checks.
Request metadata on config and response.config is limited to method, a
credential-redacted URL, and the two boolean notification-suppression controls
(molSilentErrorNotification and molSilentRateLimitNotification). Request bodies,
headers, params and all other provider options are omitted, as are credential-bearing
response headers, because errors are routinely serialized by logging transports.
status is an HTTP status when the server answered, and 0 when it did not.
A 0 means NO response exists: the request was aborted (an AbortController, a
component's effect cleanup, a route change tearing the request down) or the
network failed before anything came back. It is not an HTTP status at all, so it
says nothing about the session — an app must never treat status < 500 as
"signed out", because every aborted request on a route change would clear the
session. The correct check is isAuthFailure (status === 401 || status === 403);
isNoResponse (status === 0) identifies this case.
class HttpError extends Error {
/**
* Recognizes the shared failed-request contract without widening subclass checks.
*
* @param value - Any value to test.
* @returns True for a prototype instance, or a compatible branded value checked against the base class.
*/
static [Symbol.hasInstance](value: unknown): boolean {
return (
Function.prototype[Symbol.hasInstance].call(this, value) ||
(this === HttpError &&
typeof value === 'object' &&
value !== null &&
(value as Record<symbol, unknown>)[HTTP_ERROR_BRAND] === true)
)
}
/**
* Redacts URL userinfo and credential query/fragment values while preserving the path and
* non-secret parameters. Shared by compatible HTTP and auth error/log views.
*/
static readonly redactUrlCredentials = redactUrlCredentials
/**
* Builds a failed-request error.
*
* @param message - Human-readable message (already translated where a key exists);
* credentials in any URL it contains are redacted.
* @param status - HTTP status, or `0` when no response was received (aborted / network failure).
* @param response - Parsed response when the server answered, otherwise undefined;
* its request config and headers are sanitized for safe logging.
* @param config - The request config that failed; only its method, redacted URL and
* boolean notification-suppression controls are retained.
* @param errorKey - Translation key for the failure (`http.error.aborted` for an
* aborted request, `http.error.networkError` for a real network failure).
* @param aborted - Whether the request was aborted before a response: an
* `AbortController` signal (component cleanup, a cancelled request) or the
* browser tearing the fetch down during a navigation. Distinguishes an abort
* from a network outage on the same `status === 0`, without parsing the message.
*/
constructor(
message: string,
public status: number,
public response?: HttpResponse,
public config?: FullRequestConfig,
public errorKey?: string,
public aborted = false,
) {
super(snapshotCredentials(message))
this.name = 'HttpError'
this.response = response ? errorResponse(response) : undefined
this.config = config ? errorRequestConfig(config) : undefined
Object.defineProperty(this, HTTP_ERROR_BRAND, { value: true })
}
}
Functions
setAuthGate(next)
Registers the gate every HTTP request awaits before it is sent, or clears it
with null.
Pass a function that resolves once the session restore has settled — with the
template auth that is () => authClient.whenRestored(), which resolves
immediately when no restore is in flight, so registering it never makes a
request wait longer than the restore it was about to race anyway.
Waiting for the restore does NOT attach its token: a separately created HTTP
client needs createDefaultHttpClientWithAuthBearer({ baseURL, getToken: () => authClient.getAccessToken(), authScheme }) from
@molecule/app-bonds-default-react (or the auth client built with
createDefaultAuthClientWithHttpSync, which mirrors the token into the
bonded client) plus setAuthGate(() => authClient.whenRestored()).
The restore's own requests are never held: a request the settle function issues while it
runs goes out immediately, so setAuthGate(() => restoreSession()) cannot deadlock even
when restoreSession calls the gated client. A restore that awaits something else first
(a storage read, a Promise.resolve()) issues its request from a later continuation, which
the gate cannot recognize — that request needs skipAuthGate: true (see
RequestConfig.skipAuthGate). @molecule/app-auth's own restore needs neither because it
uses fetch rather than the bonded client.
function setAuthGate(next: (() => Promise<void>) | null): void
next— The gate, ornullto clear a previously registered one.
awaitAuthGate(request)
Awaits the registered gate, if any. Every HTTP provider calls this before it sends a request; callers never need to.
A gate that rejects (a restore that failed) is logged and cleared of consequence: the request
is sent rather than held forever, because a dead restore must not block every request for the
life of the page. The same holds for a gate that never settles — the wait is bounded by
GATE_TIMEOUT_MS, and a timeout with requests held is reported at error level naming the fix
(skipAuthGate).
function awaitAuthGate(request?: AuthGateRequest): Promise<void>
request— The request being gated, so a request the gate itself depends on can opt out (skipAuthGate) and a stalled gate can name what it held. A provider passes its own request config; a caller passing nothing gets the plain wait.
Returns: A promise that settles when the gate has released the request.
isHttpError(err)
Whether err is an HttpError or a compatible branded request failure.
@molecule/app-auth uses the same global brand for its non-ok responses, so
this also recognizes them across realms and duplicated package copies without
sharing the same prototype. Equivalent to err instanceof HttpError; subclass
instanceof checks still require the subclass's own prototype.
function isHttpError(err: unknown): err is HttpError
err— Any thrown value.
Returns: True for an HttpError or a compatibly branded request failure.
isAuthFailure(err)
Whether the server REJECTED the request's credential — the only failure that justifies clearing a session.
401 (unauthenticated/expired token) and 403 (authenticated but refused) are
the two statuses that say "this credential no longer authorizes this session".
Everything else — 0 (aborted or offline), 404 (wrong endpoint), 5xx (server
fault), a rate limit — says nothing about the credential.
function isAuthFailure(err: unknown): boolean
err— Any thrown value.
Returns: True only when err is an HttpError with status 401 or 403.
isNoResponse(err)
Whether no response was received at all: the request was aborted or the network
failed. status === 0 is not an HTTP status — it must never be read as
"the user is not signed in".
function isNoResponse(err: unknown): boolean
err— Any thrown value.
Returns: True when err is an HttpError with status 0.
isAborted(err)
Whether the request was ABORTED (an AbortController signal, or the browser
cancelling the fetch during a navigation) rather than failing on the network.
Both arrive as status === 0; this distinguishes them, so a UI can stay silent
for a cancelled request while still reporting a real outage.
function isAborted(err: unknown): boolean
err— Any thrown value.
Returns: True when err is an HttpError flagged aborted.
createFetchClient(config)
Creates a fetch-based HTTP client using the native Fetch API.
Supports request/response/error interceptors, automatic JSON serialization, auth token injection, timeout via AbortController, and 401 error handler hooks.
function createFetchClient(config?: HttpClientConfig): HttpClient
config— Client configuration including baseURL, default headers, timeout, and credentials.
Returns: A fully configured HttpClient instance.
isIdempotentRequest(method, headers)
Whether a request may be repeated at all.
function isIdempotentRequest(
method: HttpMethod,
headers: Record<string, string | undefined>,
): boolean
method— The HTTP method.headers— The request headers (anIdempotency-Keymakes POST/PATCH repeatable).
Returns: true when repeating the request cannot duplicate a side effect.
isTransientConnectionError(message)
Whether a connection-level error is transient (a restarted process refuses or resets connections; a DNS or TLS configuration error does not).
function isTransientConnectionError(message: string | undefined): boolean
message— The error message.
Returns: true for reset/refused/closed-early/timeout shapes.
parseRetryAfter(value, now)
Parse a Retry-After header into milliseconds from now.
function parseRetryAfter(value: string | undefined, now?: number): number | undefined
value— The header value (secondsor an HTTP date).now— The clock, injected for tests.
Returns: Milliseconds to wait, or undefined when absent/unparseable.
shouldRetryRequest(input)
Decide whether one failed request should be retried.
function shouldRetryRequest(input: RetryDecisionInput): boolean
input— The method, headers, status/error and attempt count.
Returns: true when the request may be repeated.
retryDelayMs(retryAfter, attempt, options, random)
Compute the wait before the next attempt.
Retry-After wins when the server sent one (it knows when the instance will
be back); otherwise exponential backoff with full jitter.
function retryDelayMs(
retryAfter: string | undefined,
attempt: number,
options?: RetryOptions | false,
random?: () => number,
): number
retryAfter— The rawRetry-Afterheader value, when present.attempt— How many retries have already been made (0 for the first).options— Policy overrides.random— Jitter source, injected for tests (defaults toMath.random).
Returns: Milliseconds to wait before retrying.
snapshotHttpErrorBody(body)
Materialize a failed response body before the synchronous HttpError capture. Unchanged bytes are cloned directly, including a Blob's BOM and every typed-array kind. Changed textual bytes retain the BOM and use a Uint8Array fallback if the original view's alignment no longer fits. Successful responses never pass through this helper.
function snapshotHttpErrorBody<T>(body: T): Promise<T>
body— A response body about to be retained on a failed request.
Returns: A scrubbed body with unchanged binary content preserved byte-for-byte.
snapshotHttpErrorResponse(response)
Read and scrub a failed response once for a retained-error reconstruction. The detached capture carries the original body kind, safe response metadata, and minimal request config, so callers such as auth never need to read the source response or its body again.
function snapshotHttpErrorResponse<T extends HttpResponse>(response: T): Promise<T>
response— The failed HTTP response to capture.
Returns: A detached, credential-scrubbed response preserving binary body bytes where safe.
unwrapList(res)
Normalize an unknown response body into a typed array.
Accepts:
- a bare array → returned as-is (cast)
{ data: T[] }envelope → the inner arrayHttpResponse<T[]>(i.e.{ data: T[], status, ... }) → the inner arrayHttpResponse<{ data: T[] }>(the response of an envelope-returning endpoint as it arrives from@molecule/app-http'sHttpClient) → the doubly-nested inner arrayHttpResponse<{ data: T[], total, limit, offset }>(a RICH pagination envelope from a pre-built@molecule/api-resource-*list endpoint) → the innerdataarray (the numerictotal/limit/offsetmake the shape unambiguous, so callers can pass the whole HttpResponse and still get the rows)- anything else →
[]
Callers commonly pass either the raw JSON body (e.g. from fetch().then(r => r.json())) or the HttpResponse returned by useHttpClient().get(...).
Both shapes are handled here so pages don't have to remember to call
unwrapList(res.data) vs unwrapList(res).
A custom envelope such as { items: [...], count: 10 } is not a data
envelope and returns []. Read its named array directly: body.items for
raw JSON, or response.data.items for an HttpResponse. Passing that
array to unwrapList is also valid; passing the enclosing object is not.
function unwrapList<T>(res: unknown): T[]
res— Raw response body OR anHttpResponseenvelope from@molecule/app-http.
Returns: A typed array T[]; never null/undefined.
unwrapSingle(res)
Normalize a response's transport/data envelopes into a typed object.
Named API fields remain intact: { record: value } stays { record: value }.
Select that field explicitly, e.g. unwrapSingle<{ record: Item }>(res)?.record.
The generic asserts the body's type; it does not validate its schema at runtime.
Accepts:
- a non-empty plain object → returned as-is (cast)
{ data: T }envelope → the inner value{ data: null },{ data: undefined },{ data: [] }, or{ data: {} }(mock-server's no-match shape) →null- an empty object
{}→null - arrays, primitives,
null,undefined→null
The "envelope contains an array → null" branch handles the case
where the mock server returns [] for unmatched endpoints but the
caller expects a single resource.
function unwrapSingle<T>(res: unknown): T | null
res— Raw response body (e.g.HttpResponse.datafrom@molecule/app-http).
Returns: The typed resource T, or null when the response shape indicates "no resource" (including the various empty envelopes above).
setAuthTokenSource(source)
Registers the token source every bonded client reads on EACH request, or removes it with
null.
Every client that receives the source — the one bonded now, any bonded later, and the
fallback getClient returns while none is bonded — is hydrated from source() and
reads it again for every request: through HttpClient.setAuthTokenResolver where the
client implements it (createFetchClient, @molecule/app-http-axios from 1.2.0), else
through a request interceptor that pushes it with setAuthToken, which a transport applying
its token after its interceptors sends on that same request and one applying it before them
from the next request on. So a restored session reaches a client bonded after the auth setup
(which holds no client reference), and a session adopted later with no auth event
(setSession, setAccessToken) never leaves the previous account's bearer on the wire.
A source that returns null means "no body token": the client sends no Authorization
header of its own (see HttpClient.setAuthTokenResolver for why a kept bearer is a
bug). A header passed per request or in a client's default headers keeps the precedence that
client's transport gives it over the client's token.
A replaced source is followed from the next request on. Removing it (null) leaves the
bonded client (and the fallback) on the token the source returned at that moment, as a
static token that setAuthToken controls from then on.
function setAuthTokenSource(source: AuthTokenResolver | null): void
source— Returns the current access token (null when signed out), ornullto remove it.
setClient(client)
Registers an HTTP client as the active singleton.
A registered setAuthTokenSource token source is applied to the client
here, so a client bonded after the auth setup resolves the restored
session's token on every request it makes.
function setClient(client: HttpClient): void
client— The HTTP client implementation to bond.
getClient()
Retrieves the bonded HTTP client. If none is bonded, returns a module-level fetch-based fallback — it is NOT bonded.
The fallback has NO baseURL — a core cannot know an app's API prefix. A relative
call then resolves against the page origin, where a dev server answers its own HTML
shell with a 200. It warns once so the misconfiguration is named instead of showing up
as a crash three components later; a scaffold bonds the shared client with its API
prefix, so the fallback only runs in an app that never bonded one.
Returning it WITHOUT bonding is what keeps a later setClient() authoritative: a
caller that captured this fallback early does not make it the app's client, so the
scaffold's client (and its token source) still takes effect for every later call.
The fallback follows a registered setAuthTokenSource source like a bonded client
does, so an app that bonds no client at all still sends the current session.
function getClient(): HttpClient
Returns: The active HTTP client, or the unbonded fallback when none is bonded.
get(url, config)
Makes a GET request using the bonded HTTP client.
function get<T = unknown>(url: string, config?: RequestConfig): Promise<HttpResponse<T>>
url— The request URL (relative to baseURL if configured).config— Optional request configuration (headers, params, timeout).
Returns: The HTTP response with typed data.
post(url, data, config)
Makes a POST request using the bonded HTTP client.
The body is data — the SECOND argument. post(url, { data: body }) sends the JSON body
{"data":body}, not body, so the API finds none of its fields at the top level; pass the
body directly (post('/users', { user })). The config is the THIRD argument.
function post<T = unknown>(
url: string,
data?: unknown,
config?: RequestConfig,
): Promise<HttpResponse<T>>
url— The request URL.data— The request body itself (never{ data: body }).config— Optional request configuration (headers, params, timeout).
Returns: The HTTP response with typed data.
put(url, data, config)
Makes a PUT request using the bonded HTTP client.
function put<T = unknown>(
url: string,
data?: unknown,
config?: RequestConfig,
): Promise<HttpResponse<T>>
url— The request URL. The body isdata— the SECOND argument, never{ data: body }.data— The request body itself.config— Optional request configuration (the third argument).
Returns: The HTTP response with typed data.
patch(url, data, config)
Makes a PATCH request using the bonded HTTP client.
function patch<T = unknown>(
url: string,
data?: unknown,
config?: RequestConfig,
): Promise<HttpResponse<T>>
url— The request URL. The body isdata— the SECOND argument, never{ data: body }.data— The request body itself (the partial update).config— Optional request configuration (the third argument).
Returns: The HTTP response with typed data.
del(url, config)
Makes a DELETE request using the bonded HTTP client.
function del<T = unknown>(url: string, config?: RequestConfig): Promise<HttpResponse<T>>
url— The request URL.config— Optional request configuration.
Returns: The HTTP response with typed data.
Constants
DEFAULT_RETRY_OPTIONS
The resolved policy used when a caller passes no options.
const DEFAULT_RETRY_OPTIONS: Required<RetryOptions>
fetchClient
Pre-created fetch client for environments where fetch is available.
null in environments without a global fetch.
const fetchClient: HttpClient | null
Available Providers
| Provider | Package |
|---|---|
| Axios | @molecule/app-http-axios |
Injection Notes
Requirements
Peer dependencies:
@molecule/app-bond^1.0.1@molecule/app-i18n^1.0.1@molecule/app-logger^1.0.4
Runtime Dependencies
@molecule/app-bond@molecule/app-i18n@molecule/app-logger
Make ALL API calls through this client (via the framework hook useHttpClient() in
React / the Vue composable) — it carries the configured baseURL, auth headers, and
interceptors. Do NOT call fetch() / axios directly in components — that bypasses auth
- base-URL config and breaks when the transport is swapped.
Two mistakes that break in preview/production (seen in real imported apps):
- Pass RELATIVE paths; never a hardcoded host. Use
'/plants'(the BONDED client'sbaseURL—'/api'in a scaffold — is prepended), NOT'/api/plants', and NEVER an absolute dev URL like'http://localhost:4000/api/…'. A hardcodedlocalhost/host works on the author's machine, then fails cross-origin (CORS) in the preview and points at the wrong server in production. The base URL is configured ONCE (viasetClient), not per call. getClient()itself knows no baseURL. The fallback client it mints when nothing is bonded hasbaseURL: '', sogetClient().get('/items')requests the PAGE origin — in dev the Vite server answers its ownindex.htmlwith a 200, and the HTML arrives asdata, and the API then validates none of the fields it was sent. A scaffold bonds'/api'; an app that builds its own client must pass{ baseURL }.- The client is PUBLIC — never put a secret in it. Anything the browser sends (an API
key, a service-role /
sk_…key, a signing secret) is visible to every user. Secrets stay in YOUR API; the browser calls your API and the API uses the secret server-side. Only a publishable/public key may ever be client-side.
Auth (the bearer token / session cookie) is attached by the bonded client's
interceptors and token source. Keep persistence in @molecule/app-auth's
AuthClientConfig.storage; use the bonded client instead of reading storage
or hand-attaching headers in each component.
An API that wants another scheme than Bearer (Authorization: Token <jwt>) passes
authScheme: 'Token' to the client's CONSTRUCTOR — setClient(createFetchClient({ baseURL, authScheme: 'Token' })), or the bonded provider's constructor
(createAxiosClient({ … }) from @molecule/app-http-axios). It is NOT a property of
getClient()'s result: that is a built client, and client.authScheme = 'Token' is a type
error (TS2339) that changes no header. Do not hand-write a fetch wrapper for the scheme either.
Header names are case-insensitive: request headers replace defaults with the same name.
createFetchClient applies a nonempty static or resolved auth token AFTER request
interceptors, replacing any default, request or interceptor Authorization header in any
spelling. Clear the token (and any token resolver) or use a separate client to send another
credential. The Axios bond retains Axios's precedence: explicit default/request headers and
request interceptors can override the client's token.
A request made while the session is still being restored WAITS for that restore, so a page
that fetches viewer-dependent data on mount (account settings, a dashboard, or a
saved-item state) cannot go out unauthenticated and answer for an anonymous viewer. The auth
bond registers that wait with setAuthGate; apps that bond auth through
@molecule/app-bonds-default-react get it without doing anything. An app with its own session
module registers its own: setAuthGate(() => session.whenRestored()).
Waiting for the restore does NOT attach the token: a client created beside the auth bond needs
createDefaultHttpClientWithAuthBearer({ baseURL, getToken: () => authClient.getAccessToken(), authScheme }) from @molecule/app-bonds-default-react (or an auth client built with
createDefaultAuthClientWithHttpSync, which registers the auth client's token source with
setAuthTokenSource: the client reads it on each request, so a session adopted mid-page by
setSession() or an OAuth callback's setAccessToken() is sent instead of the previous
account's token — setAuthTokenSource says which request first carries it on a transport
without setAuthTokenResolver), because setAuthGate alone sends no Authorization header.
The gate never holds its own restore's request. A request the settle function issues
while it runs (its call reaches this client before the function awaits anything) is part of
the restore it is waiting for, so it goes out immediately — setAuthGate(() => restoreSession()) does not deadlock even when restoreSession uses this client. A restore
that awaits something else first and only then calls the client reaches it after that
window, and that request must opt out of the gate: http.get(currentUserEndpoint, { skipAuthGate: true }). Without the opt-out the gate waits on itself, the restore never
settles, and every request the gate holds stalls until it times out (3 s).
@molecule/app-auth's own restore does not need it (it calls fetch, not this client).
A failed request's status is 0 when NO response arrived — never read it as
"signed out". An aborted request (an AbortController signal, a component's
effect cleanup, a route change tearing the fetch down) and a network outage both
throw an HttpError with status === 0; the aborted ones also carry
aborted: true and the http.error.aborted key, the rest http.error.networkError.
Neither says anything about the session. To decide whether a session ended, use
isAuthFailure(err) (401/403 only); isNoResponse(err) identifies the no-response
case so a caller can stay silent instead of reporting an outage. Do not write
err instanceof HttpError && err.status < 500 as a sign-out check — it clears
the session on every aborted navigation request.
Every non-ok response rejected by @molecule/app-auth also satisfies
err instanceof HttpError and isHttpError(err): its status and response.data
are the same HTTP status and parsed body exposed as AuthError.status and
AuthError.body, while it remains an I18nError. Both checks accept the shared
brand across duplicated package copies. Subclass checks keep their ordinary
prototype semantics; a branded base error is not an instance of every subclass.
Translations
Translation strings are provided by @molecule/app-locales-http.