@molecule/app-http
Core interface · http · App (browser) · v1.11.0 · 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. Use the configured client for the visitor's session.
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.
List responses: unwrapList<T>(response) accepts a bare array, a data envelope,
or a named list such as { articles: T[], articlesCount: number } or
{ items: T[], count: number }, in both raw-body and HttpResponse forms. It selects
the single collection array only when every sibling is list metadata (pagination,
meta, links, or a numeric <collection>Count / <collection>_count). Metadata keys
are not collection names. Resource objects with fields such as id or subtotal,
multiple collection arrays, and unsupported or empty mock responses return [].
For a resource containing an array, read its field explicitly; the generic casts
the rows without validating the server's schema.
Single responses 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. Use the configured client for the visitor's session.
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
HttpAuthRestore
Wiring for an application that restores its session through its own HTTP client.
interface HttpAuthRestore {
/** The application's configured transport, including its token resolver and interceptors. */
client: Pick<HttpClient, 'request'>
/** Restore the session using the supplied request function, which bypasses this gate. */
restore: (request: HttpClient['request']) => Promise<void>
}
HttpClient
HTTP client interface.
All HTTP providers must implement this interface. An explicit text, blob or arraybuffer parser determines the data type even when a JSON generic is supplied. Keep JSON as the default for mutations returning a record. A successful DELETE with no body already resolves with null data.
Every verb also takes a URL alone, through a signature with the same three parameters on every
verb, so a verb chosen at runtime (client[verb](url)) type-checks and a wrapper can implement
a verb with an arrow (get: (url, config) => inner.get(url, config)). With a body or a config,
choose the verb through request({ method, url, data }) instead: the second argument is the
body for post/put/patch but the config for get/delete, so one call cannot serve both.
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 & { responseType: 'text' },
): Promise<HttpResponse<string>>
request<T = unknown>(
config: FullRequestConfig & { responseType: 'blob' },
): Promise<HttpResponse<Blob>>
request<T = unknown>(
config: FullRequestConfig & { responseType: 'arraybuffer' },
): Promise<HttpResponse<ArrayBuffer>>
request<T = unknown>(config: FullRequestConfig): Promise<HttpResponse<T>>
/**
* Makes a GET request.
*/
get<T = unknown>(
url: string,
config: RequestConfig & { responseType: 'text' },
): Promise<HttpResponse<string>>
get<T = unknown>(
url: string,
config: RequestConfig & { responseType: 'blob' },
): Promise<HttpResponse<Blob>>
get<T = unknown>(
url: string,
config: RequestConfig & { responseType: 'arraybuffer' },
): Promise<HttpResponse<ArrayBuffer>>
get<T = unknown>(url: string, config?: undefined, unused?: undefined): Promise<HttpResponse<T>>
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 & { responseType: 'text' },
): Promise<HttpResponse<string>>
post<T = unknown>(
url: string,
data: unknown,
config: RequestConfig & { responseType: 'blob' },
): Promise<HttpResponse<Blob>>
post<T = unknown>(
url: string,
data: unknown,
config: RequestConfig & { responseType: 'arraybuffer' },
): Promise<HttpResponse<ArrayBuffer>>
post<T = unknown>(url: string, data?: undefined, config?: undefined): Promise<HttpResponse<T>>
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 & { responseType: 'text' },
): Promise<HttpResponse<string>>
put<T = unknown>(
url: string,
data: unknown,
config: RequestConfig & { responseType: 'blob' },
): Promise<HttpResponse<Blob>>
put<T = unknown>(
url: string,
data: unknown,
config: RequestConfig & { responseType: 'arraybuffer' },
): Promise<HttpResponse<ArrayBuffer>>
put<T = unknown>(url: string, data?: undefined, config?: undefined): Promise<HttpResponse<T>>
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 & { responseType: 'text' },
): Promise<HttpResponse<string>>
patch<T = unknown>(
url: string,
data: unknown,
config: RequestConfig & { responseType: 'blob' },
): Promise<HttpResponse<Blob>>
patch<T = unknown>(
url: string,
data: unknown,
config: RequestConfig & { responseType: 'arraybuffer' },
): Promise<HttpResponse<ArrayBuffer>>
patch<T = unknown>(url: string, data?: undefined, config?: undefined): Promise<HttpResponse<T>>
patch<T = unknown>(url: string, data?: unknown, config?: RequestConfig): Promise<HttpResponse<T>>
/**
* Makes a DELETE request.
*/
delete<T = unknown>(
url: string,
config: RequestConfig & { responseType: 'text' },
): Promise<HttpResponse<string>>
delete<T = unknown>(
url: string,
config: RequestConfig & { responseType: 'blob' },
): Promise<HttpResponse<Blob>>
delete<T = unknown>(
url: string,
config: RequestConfig & { responseType: 'arraybuffer' },
): Promise<HttpResponse<ArrayBuffer>>
delete<T = unknown>(url: string, config?: undefined, unused?: undefined): Promise<HttpResponse<T>>
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`. */
setAuthTokenResolver?(resolver: AuthTokenResolver | null): void
/**
* Registers a handler for authentication errors (401), with the rejected request's metadata.
*
* @param handler - Receives the method, URL and credential state of the rejected request.
* @returns An unsubscribe function.
*/
onAuthError(handler: (event: HttpAuthErrorEvent) => void): () => void
}
(The longest member comment is shortened to its first sentence to fit; the full declaration is in node_modules/@molecule/app-http/dist/client.d.ts.)
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
}
KeepaliveRequest
What a client knows about a request when it decides on keepalive.
interface KeepaliveRequest {
/** HTTP method. */
method: string
/** The request URL, absolute or relative to the page. */
url: string
/** The body as it will be sent (a JSON string, a Blob, bytes), or undefined for none. */
body?: unknown
/** The caller's own `keepalive` choice, which always wins. */
keepalive?: boolean
}
KeepaliveReservation
A keepalive decision, holding its share of the in-flight budget until released.
interface KeepaliveReservation {
/** Whether to send the request with `keepalive`. */
keepalive: boolean
/** Return the reserved bytes; call once the request has settled. Safe to call twice. */
release(): void
}
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
}
HttpAuthErrorEvent
Request metadata passed to a client auth-error listener when the server responds with 401.
interface HttpAuthErrorEvent {
/** The HTTP method after request interception. */
readonly method: HttpMethod
/** The request's configured URL after interception, with credentials redacted. */
readonly url: string
/**
* Whether the request supplied an Authorization or Cookie header, configured transport auth,
* or explicitly opted into sending cookies. Browsers do not expose implicit cookies to the
* client, so consumers also need the app's auth state to decide whether a visitor is signed out.
*/
readonly sentCredentials: boolean
}
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).
*
* For a custom HTTP restore, `setAuthGate({ client, restore })` provides a request function
* that applies this option automatically.
*
* 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
/**
* Keep the fetch client's configured timeout when a caller also supplies a signal.
* Use this when the signal represents cancellation independent of the timeout,
* such as a session change during a write.
*/
timeoutWithSignal?: boolean
/**
* Keep the request running when the page navigates away or closes before it finishes — fetch's
* own `keepalive`. The bundled clients already do this for a write (POST, PUT, PATCH, DELETE) to
* the page's own origin with a body of at most 8 KB, so a favorite or a save followed at once by
* a navigation still reaches the API; nothing needs to be set for that. Pass `true` for anything
* else that must outlive the page (a cross-origin write, a beacon on `pagehide`) and `false` to
* let a navigation cancel a write. The browser caps the bodies of in-flight keepalive requests
* at 64 KB in total, so not for uploads.
*
* ```typescript
* await http.post('https://events.example.com/v1/track', event, { keepalive: true })
* ```
*/
keepalive?: boolean
/**
* 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.
For an app restoring its own session through HTTP, pass { client, restore } after
configuring the client. This starts one restore. The callback's request function bypasses
the gate even after an asynchronous storage read, and other requests wait for it to settle.
The returned promise resolves when the restore settles.
void setAuthGate({
client,
async restore(request) {
const { data } = await request<Profile>({ method: 'GET', url: currentProfilePath })
session.setProfile(data)
},
})
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: HttpAuthRestore): Promise<void>
next— A session wait function, HTTP restore wiring, ornullto clear the gate.
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.
serverErrorMessage(err)
The message the server sent with a failed request: the error (else
message) string of its JSON body, or undefined when the server sent none
(no response, an empty body, a non-JSON body).
Show this, then a translated fallback, never err.message: an
HttpError's own message is the transport's status line (Request failed with status code 403), written for logs. Molecule API routes answer a
refused request with { error } already translated for the user (a wrong
password, an invalid two-factor code, a declined checkout).
catch (err) {
setError(serverErrorMessage(err) ?? t('settings.failedToDeleteAccount', undefined, {
defaultValue: 'Failed to delete account.',
}))
}
function serverErrorMessage(err: unknown): string | undefined
err— Any thrown value.
Returns: The server's non-empty message, or undefined.
requestBodyBytes(body)
The byte length of a request body, or null when it cannot be known up front (a form, a stream).
function requestBodyBytes(body: unknown): number | null
body— The body as it will be sent.
Returns: Its size in bytes, or null.
reserveKeepalive(request)
Decide whether a request is sent with keepalive and reserve its body bytes while it runs.
The caller's explicit keepalive always wins. Otherwise a write (any method but GET, HEAD and
OPTIONS) to the page's own origin whose body size is known, at most
KEEPALIVE_DEFAULT_MAX_BODY_BYTES, and fits the remaining
KEEPALIVE_IN_FLIGHT_BUDGET_BYTES is kept alive. Reads, cross-origin requests (the default
stays on the same-origin case, which needs no CORS preflight), forms, streams and large bodies
are sent as before; any of them can still ask for keepalive: true.
function reserveKeepalive(request: KeepaliveRequest): KeepaliveReservation
request— The request's method, URL, body and explicit choice.
Returns: The decision; call release() once the request settles.
keepaliveBytesInFlight()
The keepalive body bytes currently reserved (for tests and diagnostics).
function keepaliveBytesInFlight(): number
Returns: The reserved byte count.
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[] }with optional list metadata → the inner array- a named list such as
{ articles: T[], articlesCount: number }or{ items: T[], count: number }→ the named array HttpResponse<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 arrayHttpResponsewrapping any supported list envelope → the inner array- 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).
An envelope must have exactly one collection array; its other keys may only
be pagination metadata (count, total, page, limit, cursors, meta,
links, etc.) or a numeric count named after the collection (itemsCount
or items_count). Metadata keys themselves are not collection names.
Resource fields such as id, name or subtotal, and multiple collection
arrays, make the body ambiguous and return []. Select the intended array
explicitly in those cases. No resource fields are discarded, even when a
resource owns a data array. Raw bodies and HttpResponse bodies use the same
rule; the generic casts the rows without validating their schema.
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. Before setup, returns a live handle which uses a fetch fallback until the application bonds its transport. 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.
A service imported before setup may capture this handle, or one of its methods.
Each invocation uses the current bonded transport, including its API prefix,
interceptors and token source. Explicitly constructed clients remain independent.
Subscriptions and configuration writes apply to the transport active when made;
configure the application transport before registering interceptors on it.
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
KEEPALIVE_DEFAULT_MAX_BODY_BYTES
The largest request body a write is kept alive with by default.
const KEEPALIVE_DEFAULT_MAX_BODY_BYTES: number
KEEPALIVE_IN_FLIGHT_BUDGET_BYTES
The in-flight keepalive body bytes the default stays under. Browsers refuse a keepalive request once the bodies of a document's in-flight keepalive requests would pass 64 KiB.
const KEEPALIVE_IN_FLIGHT_BUDGET_BYTES: number
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.4expo>=53.0.0 (optional)
Runtime Dependencies
@molecule/app-bond@molecule/app-i18n@molecule/app-loggerexpo(optional)
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. Its same-origin fallback while 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'. A handle captured before setup follows the client bonded later, including extracted methods. An explicitly constructed client stays independent and 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.
client.onAuthError(handler) calls handler({ method, url, sentCredentials }) on 401.
The event describes the rejected request after interception and token injection. Its URL
is credential-redacted, and explicit cookie inclusion counts as credentialed.
A different account does not require a hand-written transport. For demo data,
an operator action, or another tenant's token, construct a separate package client in
the composition root and pass it to the helper as HttpClient. Leave it unbonded:
setAuthTokenSource affects the bonded client, not an independent instance. Set the
independent client's own token with setAuthToken(accountToken) (or a live
setAuthTokenResolver). Do not call setClient, change the visitor's auth client,
or override the visitor's resolver to act as another account. Each independent client
needs its own baseURL and authScheme. This is package reuse, not another fetch wrapper.
The global session-restore gate still applies. Use the request's skipAuthGate: true
only when that request is independent of the visitor's restore.
// In the composition root. Pass this client to the account-specific helper.
import { createFetchClient } from '@molecule/app-http'
const scoped = createFetchClient({ baseURL: '/api', authScheme: 'Token' })
scoped.setAuthToken(accountToken)
const response = await scoped.post('/stock', { name: 'Paper' })
// response.data is the parsed body. The visitor's client and session are unchanged.
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 can start its restore and register the wait together with
setAuthGate({ client, restore }).
Use the provided request inside that callback. It uses the configured transport and
bypasses the gate, including after awaits and with intercepting HTTP providers.
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.
Show a failed request as serverErrorMessage(err) ?? t(fallbackKey, …), never
err.message. An HttpError's message is the transport's status line (Request failed with status code 403), written for logs; molecule API routes answer a refused
request with a translated { error } body (a wrong password, an invalid code), which
serverErrorMessage returns.
Translations
Translation strings are provided by @molecule/app-locales-http.