@browsercore/fetch

A developer-facing high-level HTTP API. Composes every lower-level package
(transport, tls, http1, http2, profiles, cookies) into a single fetch() surface
with browser-accurate TLS + HTTP fingerprints.
Install
npm install @browsercore/fetch
Most users want browsersmith instead. It's the composition root that ships a ready-made Node Platform, profiles, and cookie jar. Install fetch directly when you bring your own Platform: custom transports, embedded runtimes, tests.
Responsibility
URL parsing, connection reuse, profile loading, redirect policy, cookie
integration, and automatic protocol selection (h2 vs h1.1 via ALPN). Near the
top of the dependency stack: only the composition roots (browsersmith,
@browsercore/crawlee) and the @browsercore/testing/http3/devtools
packages sit above this one.
IP-literal hosts
An IP-literal URL (http://127.0.0.1:8080/, https://[::1]:8443/) is
dialled like Chrome dials it:
- No DNS — in BOTH connect strategies (
"chrome" — the default — and
the opt-in "happy-eyeballs-v3"; the guarantee lives in
@browsercore/transport, so every strategy inherits it). The WHATWG URL
parser's hostname (bracketed IPv6 forms keep their brackets) reaches the
dial layer, which recognizes the literal and connects directly — the
injected resolver is never consulted, at any point in the connection's
lifetime (no alternate-family lookup on the slow mark either). IPv4
dotted-quad, bare and bracketed IPv6, and the IPv4-mapped textual form all
dial by literal; anything else resolves through platform.network.dns as
before. (The URL parser itself has already normalized the exotic IPv4
spellings — http://0x7f.1/, http://2130706433/ — to dotted decimal,
and rejects IPv6 zone ids.)
- Host /
:authority keep the brackets ([::1]:8443; a default-port
URL sends Host: [::1]).
- Certificate identity: the leaf's
iPAddress SAN entries are matched
byte-exactly for an IP-literal host in every verifying mode (the default
hostname check included — see @browsercore/tls), per family — IPv4
against 4 octets, IPv6 against 16, and the IPv4-mapped textual form is a
16-octet comparison that never folds to 4; the CommonName and wildcards
never match an IP.
- TLS SNI: the ClientHello carries no
server_name extension for a
literal host (RFC 6066 §3; Chrome's own behavior).
- Redirects and proxies behave the same: a literal
Location target dials
directly, and a literal target through an HTTP CONNECT or SOCKS5 proxy is
forwarded to the proxy as the literal.
Runtime dependencies via Platform
fetch has no runtime bindings of its own. Every capability it needs at
runtime (events, TCP, DNS, crypto, compression, time) is injected through a
single Platform object
that browsersmith (the composition root) assembles and passes down:
import { fetch } from "@browsercore/fetch";
import { createPlatform } from "browsersmith";
// browsersmith builds the Platform; fetch consumes it. No global singletons,
// no fallback providers: fetch throws if a required capability is missing.
const platform = createPlatform();
const response = await fetch("https://example.com", { profile: "chrome-140" }, platform);
createClient resolves each capability from platform, falling back to an
explicit individual option when one is provided (useful to override a single
adapter):
| Capability |
Platform field |
Individual fallback |
| events |
platform.events |
options.events |
| TCP |
platform.network.tcp |
options.net |
| DNS |
platform.network.dns |
options.dns |
| crypto |
platform.crypto.provider |
options.crypto |
| compression |
platform.compression |
options.compression |
| time |
platform.time |
options.clock |
events is mandatory and has no fallback; fetch never creates its own provider.
Time: platform.time is honored
Every timer fetch arms runs on the canonical Clock from
@browsercore/contracts, resolved once per client as
options.clock ?? platform.time ?? systemClock:
- the whole-request timeout (
timeoutMs, default 30 000) that backs
FetchTimeoutError, and
- the pool idle-eviction timers (
idleTimeoutMs, default 30 000).
systemClock (exported) delegates to the platform globals (Date.now(),
performance.now(), setTimeout/clearTimeout). For deterministic testing,
inject a manual-advance Clock via
options.clock (or platform.time): both timeout kinds then fire at exact
virtual instants with zero real timers. See tests/deterministic-clock.test.ts.
import { createClient, type Clock } from "@browsercore/fetch";
const manual: Clock = { /* now, monotonic, sleep, setTimeout, clearTimeout */ };
const client = createClient({ clock: manual, timeoutMs: 500 });
Public API
import { fetch, createClient, FetchTimeoutError } from "@browsercore/fetch";
// One-shot convenience fetch (creates + closes a default client).
// Requires a Platform (see "Runtime dependencies via Platform" above).
const response = await fetch("https://example.com", { profile: "chrome-140" }, platform);
console.log(response.status, await response.text());
// Reusable client for connection pooling + defaults:
const client = createClient({ profile: "chrome-140", platform });
try {
const r1 = await client.fetch("https://example.com");
const r2 = await client.fetch("https://example.com/api", { method: "POST" });
} finally {
await client.close();
}
Connection pooling
Connections are pooled per origin (host:port) and reused across requests. A
connection unused for idleTimeoutMs (default 30 000, 0 disables) is closed
and evicted. Connections the SERVER closes while pooled (LB idle timeouts,
GOAWAY, FINs) are evicted the moment the transport reports the close; a request
that would otherwise take an already-dead connection redials transparently
within the same request. Client-initiated closes (client.close()) and idle
eviction are unaffected.
Timeout and abort handling acts on the connection the failing request actually
used, never on the pool key: a request that force-closes its connection cannot
touch a different connection that a concurrent request established for the
same origin in the meantime (such a connection is handed to its caller without
being pooled and is closed when the caller returns it).
Resending on a stale connection
A request that fails on a REUSED keep-alive connection before ANY response
headers is transparently resent on a fresh connection, with byte-identical
bytes. This is the browser's specified behaviour — Chromium 140.0.7339.100,
net/http/http_network_transaction.cc:
bool HttpNetworkTransaction::ShouldResendRequest() const {
bool connection_is_proven = stream_->IsConnectionReused();
bool has_received_headers = GetResponseHeaders() != nullptr;
// NOTE: we resend a request only if we reused a keep-alive connection.
// This automatically prevents an infinite resend loop because we'll run
// out of the cached keep-alive connections eventually.
return connection_is_proven && !has_received_headers;
}
The rule, in plain words:
- When: the request ran on a pooled connection the pool had handed out
before (a "reused" connection — the pool reports this per take, mirroring
Chromium's
IsConnectionReused()), nothing was received — no final response
headers AND no informational 1xx — and the failure is a connection failure:
HTTP/1.1's ConnectionClosedError (transport closed with no or partial
headers, write on a dead connection, request refused on an already-closed
connection), or on HTTP/2 a graceful GOAWAY (NO_ERROR), RST_STREAM with
REFUSED_STREAM, the preface-ping failure, or the session's transport/TLS
death. "Nothing received" is observed per protocol through a hook: HTTP/1.1's
onInformationalResponse fires for each interim 1xx (a 100 Continue or
103 Early Hints) drained before the final response, HTTP/2's
onResponseHeaders fires when a response HEADERS block is decoded — and
after either has fired, Chromium's HasReceivedResponse() is true (a 1xx
resets response_.headers non-null, http_network_transaction.cc ≈1676), so
a death after it SURFACES instead of resending.
- Any method: POST/PUT/DELETE resend exactly like GET (Chromium's
ResetConnectionAndRequestForResend rebuilds the request from the same data
without re-evaluating cookies). The wire request is built once per request —
headers including the Cookie header and body bytes — and the SAME bytes are
sent on the fresh connection. Set-Cookie is handled only on the response
that is finally returned. A failure on a FRESH connection, or after response
headers (HTTP/1.1's ResponseTruncatedError), always surfaces.
- Budgets (per request): connection-error resends cap at
MAX_RESENDS_ON_CONNECTION_ERRORS = 50 (Chromium's historical
kMaxRetryAttemptsOnConnectionErrors; in practice self-limiting, because a
resent request lands on a fresh connection, which is never "reused"). The
HTTP/2 refused-stream class (graceful GOAWAY, REFUSED_STREAM, ping
failure — Chromium's ERR_HTTP2_SERVER_REFUSED_STREAM /
ERR_HTTP2_PING_FAILED, retried with NO reuse precondition) caps at
MAX_RESENDS_REFUSED_STREAM = 2 (Chromium's kMaxRetryAttempts). Non-graceful
GOAWAY (any other code), RST_STREAM with any other code, frame/HPACK
failures, timeouts and aborts are never resent.
- 408: a 408 response on a REUSED HTTP/1.1 connection triggers exactly one
resend (the connection is closed first); on a fresh connection or on HTTP/2
the 408 is returned to the caller (Chromium: "retry the request for HTTP/1.1
but not HTTP/2 or QUIC because those multiplex requests and have no need for
408").
- Timeout is per attempt:
timeoutMs applies to each attempt; a resent
request gets a fresh full window. The abort signal is honoured between
attempts — an aborted request is never resent. An aborted request rejects
with a FetchError carrying kind: "AbortError" (the class itself is
internal; match on kind).
- Redirects are unaffected: the resend happens inside the per-hop
dispatch, before redirect handling sees anything.
- Opt-out:
retryOnStaleConnection: false — on the client
(FetchClientOptions) or per request (FetchOptions, request wins when
present). false disables resending: every failure surfaces, one dial per
request.
- Observability: every resend emits exactly one frozen
requestResend event on the injected EventProvider
(RequestResendEvent: attempt number, budget class, reason, protocol,
whether the connection was reused, whether response headers had started,
method, host, path, and the error's kind/name chain). Fetch has no logger —
there is no console output anywhere.
HTTP/1.1 over TLS
Both ALPN outcomes on an https: origin are fully supported. The TLS
connection is adapted to the Transport surface by an adapter that delivers
every decrypted record exactly once, in order, through whichever consumption
path the protocol layer uses: HTTP/1.1 (push-driven — it listens for data
events) receives records through the adapter's pump; HTTP/2 (pull-driven)
continues to read records on demand.
When the TLS stream terminates, the adapter emits error at most once and
then exactly one close (mirroring a TCP socket's error-then-close ending).
This holds even for a SILENT TLS death (the underlying read fails without the
TLS connection reporting anything): the adapter synthesizes the closing
close itself, so an in-flight HTTP/1.1 request rejects promptly instead of
hanging and data consumers observe the end of the stream. Pending read()
callers reject as well. The pool participates: an https entry is checked for
liveness on its TLS adapter at handout, and a TLS stream that dies while the
connection sits idle evicts the entry, so the next request dials fresh and is
never written to a dead stream.
Proxied requests
Every request (or a whole client, via FetchClientOptions.proxy) can be
tunneled through an HTTP CONNECT or SOCKS5/5h proxy via @browsercore/proxy.
Proxied connections are pooled per origin+proxy pair, so different proxies never
share a connection. Proxy failures surface as FetchProxyError with the
wrapped kind preserved on proxyKind.
const client = createClient({
platform,
proxy: { scheme: "socks5h", host: "127.0.0.1", port: 1080 }, // client default
});
// Per-request proxy replaces the client default:
const r = await client.fetch("https://example.com", {
proxy: { scheme: "http", host: "127.0.0.1", port: 8080 },
});
Certificate verification (opt-in trust anchors)
FetchClientOptions.trustAnchors opts in to certificate chain verification
with raw DER-encoded trust-anchor (root) certificates. When present and
non-empty, EVERY TLS connection the client makes — direct or proxied (TLS
always terminates at the origin, never at the proxy) — is verified against
those anchors IN ADDITION to the hostname check.
- Without
trustAnchors, no certificate-path validation runs. Absent or
empty → the connection verifies the hostname and runs the
signature-algorithm sweep, and builds no certificate path — the default
(path validation on by default would break consumers behind TLS-inspecting
proxies or talking to private CAs).
- With
trustAnchors, the server's chain is built to one of the anchors
and validated according to the @browsercore/tls certificate-validation
rules — see the certificate-validation notes in the README of
@browsercore/tls for the exact checks and their current limitations. The
one limitation stable across this whole stack: there is NO revocation
checking (no CRL, no OCSP) anywhere.
- Anchors are copied + frozen at
createClient: mutating the caller's
array or buffers afterwards never changes what later connections verify.
- Validation is eager: each entry must be a non-empty byte view (a
Uint8Array; any one-byte-per-element view, e.g. a Buffer or a
cross-realm Uint8Array, is accepted) of raw DER bytes; violations raise
FetchConfigError at createClient, never a per-connection error.
- Failure surfacing: a failed verification raises the existing
FetchError with the underlying TLS error intact on cause.
- Client-level only: a per-request override would need its own
connection-pool key, so there is deliberately no per-request option —
create a second client instead.
Obtain raw DER roots from a PEM with the tls package's pemToDer:
import { createClient } from "@browsercore/fetch";
import { pemToDer } from "@browsercore/tls";
const client = createClient({
platform,
trustAnchors: [pemToDer(rootPem), pemToDer(privateCaPem)],
});
TLS policy pass-through (tls)
FetchClientOptions.tls carries the certificate-verification POLICY of
@browsercore/tls onto every TLS connection the client dials — direct and
proxied (TLS always terminates at the origin, never at the proxy) — with
TlsPolicy being exactly the slice of tls's TlsOptions that package
documents as caller policy: certificateVerification
("none" / "chrome" / "custom"), the certificatePolicy sub-policy of
the "chrome"/"custom" modes, and the raw-DER trustAnchors field. The
object is threaded VERBATIM into the connectTls options: fetch adds no
policy of its own, and every default on the surface is tls's default — the
README of @browsercore/tls ("Certificate verification modes") owns the
per-mode semantics and the sub-policy flags.