Skip to content
StopMakingThatBigFacePublic

Repository files navigation

node-wreq

NPM Version ESM CJS Platforms

node-wreq is a thin Node.js wrapper around 0x676e67's wreq — a Rust HTTP client exposing its full power to JavaScript.

Use it when you need low-level control over the network layer: TLS configuration, transport fingerprinting, browser impersonation, or fine-grained HTTP/WebSocket behavior that standard Node.js clients simply don't expose.

Tip

why does this exist?

Node.js ships with a built-in https module, and the ecosystem offers popular clients like axios, got, and node-fetch — but all of them are built on top of OpenSSL via Node's tls module, which exposes no control over low-level TLS handshake parameters. This makes it fundamentally impossible to emulate real browser network behavior from pure JavaScript.

  • HTTP/1 over TLS

    Node.js HTTP clients normalize headers to lowercase internally, which is compliant with HTTP/2 semantics but breaks compatibility with some WAFs that enforce case-sensitive header validation on HTTP/1 requests. This wrapper preserves header case exactly as specified, preventing requests from being silently rejected.

  • HTTP/2 over TLS

    Fingerprints like JA3, JA4, and Akamai HTTP/2 are derived from the specifics of the TLS handshake and HTTP/2 SETTINGS frames — cipher suite ordering, TLS extensions, ALPN values, HPACK header compression parameters, and more. Node.js exposes none of these through its tls or http2 APIs. You simply cannot spoof them from JS land, no matter the library. This package solves that at the native layer, giving you fine-grained control over TLS and HTTP/2 extensions to precisely match real browser behavior.

  • Device Emulation

    Because TLS and HTTP/2 fingerprints evolve slowly relative to browser release cycles, a single fingerprint profile often covers many browser versions. 100+ pre-built browser device profiles are bundled, so you don't have to figure out the right combination of settings yourself.

TLS and HTTP/2 fingerprinting is actively used by major bot protection and WAF providers — including Cloudflare Bot Management, AWS WAF (Bot Control + CloudFront JA3 headers), Google Cloud Armor, Akamai (which maintains its own HTTP/2 fingerprint format on top of JA3/JA4), ServicePipe (a Russian DDoS protection and WAF provider), and various specialized anti-bot services like DataDome and PerimeterX. Correctly emulating a browser's TLS handshake and HTTP/2 SETTINGS frames is a hard requirement to get past these layers undetected.

TLS Fingerprinting with JA3 and JA3S

JA3/JA4 Fingerprint — Cloudflare Bot Solutions

TLS Fingerprinting: How It Works & How to Bypass It

Note

This only covers the transport layer. It does not help bypass JavaScript-based challenges (Cloudflare Turnstile, Akamai sensor data, Kasada, etc.), CAPTCHA, or behavioral analysis — those require a different approach entirely

install

npm install node-wreq

Node.js 20+ is required.

contents

🌐   fetch

🧩   client — shared defaults, reusable config.

🪝   hooks — request lifecycle, dynamic auth, retries, etc.

🔌   websockets

🧪   networking / transport knobs — TLS, HTTP/1, HTTP/2 options; header ordering, mTLS and custom CAs; DNS controls.

⚡ quick start

import { fetch } from 'node-wreq';

const response = await fetch('https://httpbin.org/get', {
  browser: 'chrome_149',
});

console.log(response.status);
console.log(await response.json());

If you keep repeating config, move to a client:

import { createClient } from 'node-wreq';

const client = createClient({
  baseURL: 'https://httpbin.org',
  browser: 'chrome_149',
  headers: {
    'x-client': 'node-wreq',
  },
  retry: 2,
});

const response = await client.fetch('/anything', {
  query: { from: 'client' },
});

console.log(response.status);
console.log(await response.json());

🌐 fetch   ·   ↑

simple GET

import { fetch } from 'node-wreq';

const response = await fetch('https://httpbin.org/get', {
  browser: {
    profile: 'firefox_151',
    platform: 'linux',
    http2: true,
    headers: true,
  },
  query: {
    source: 'node-wreq',
    debug: true,
  },
  timeout: 15_000,
});

const body = await response.json<{ args: Record<string, string> }>();

console.log(response.ok);
console.log(body.args);

JSON POST

import { fetch } from 'node-wreq';

const response = await fetch('https://api.example.com/items', {
  method: 'POST',
  browser: 'chrome_149',
  headers: {
    'content-type': 'application/json',
  },
  body: JSON.stringify({
    name: 'example',
    enabled: true,
  }),
  throwHttpErrors: true,
});

console.log(await response.json());

upload FormData

FormData request bodies work like fetch. By default, node-wreq generates a ----WebKitFormBoundary... boundary so the multipart envelope matches browser traffic as well as the TLS and HTTP fingerprints do. File parts are encoded by native wreq multipart support and streamed with backpressure instead of buffering the complete form in memory.

const formData = new FormData();

formData.append('alpha', '1');
formData.append('upload', new File(['hello'], 'hello.txt', { type: 'text/plain' }));

const response = await fetch('https://api.example.com/upload', {
  method: 'POST',
  body: formData,
  // Optional: multipartBoundary: '----my-explicit-boundary',
});

console.log(await response.json());

build a Request first

import { Request, fetch } from 'node-wreq';

const request = new Request('https://httpbin.org/post', {
  method: 'POST',
  headers: {
    'content-type': 'application/json',
  },
  body: JSON.stringify({ via: 'Request' }),
});

const response = await fetch(request, {
  browser: 'chrome_149',
});

console.log(await response.json());

read extra metadata

fetch() returns a fetch-style Response, plus extra metadata under response.wreq.

const response = await fetch('https://example.com', {
  browser: 'chrome_149',
});

console.log(response.status);
console.log(response.headers.get('content-type'));

console.log(response.wreq.cookies);
console.log(response.wreq.setCookies);
console.log(response.wreq.timings);
console.log(response.wreq.redirectChain);

If you need a Node stream instead of a WHATWG stream:

const readable = response.wreq.readable();

readable.pipe(process.stdout);

readable() consumes the body, the same as reading response.body: a body can be read once, so text(), json() and the other readers reject afterwards. Call response.clone() first if you need the body twice (the clone buffers what the other copy has not read yet).

🧩 client   ·   ↑

Use createClient(...) when requests share defaults. A client also owns reusable native connection and TLS-session pools; it is not just a JavaScript defaults wrapper.

  • baseURL
  • browser profile
  • headers
  • proxy
  • timeout
  • hooks
  • retry policy
  • cookie jar

How per-call options combine with client defaults:

  • a per-call option replaces the default; an option passed as undefined counts as not passed
  • headers: a per-call header replaces every default value of that name; the remaining defaults go first, then the per-call headers in the order you gave them. With a Request input, its headers are the per-call headers unless init.headers is given (which replaces them, as in Fetch)
  • query, context: merged key by key; hooks: default hooks run first; retry: merged field by field
  • baseURL uses standard URL resolution (new URL(input, baseURL)), so the trailing slash matters:
baseURL input result
https://api.example.com/v1/ users https://api.example.com/v1/users
https://api.example.com/v1 users https://api.example.com/users
https://api.example.com/v1/ /users https://api.example.com/users
any https://x.dev/ https://x.dev/ (base ignored)
  • query params are added before any #fragment; a key already in the URL's query is replaced, the rest of the existing query is kept exactly as written

shared defaults

import { createClient } from 'node-wreq';

const client = createClient({
  baseURL: 'https://api.example.com',
  browser: 'chrome_149',
  timeout: 10_000,
  headers: {
    authorization: `Bearer ${process.env.API_TOKEN}`,
  },
  retry: {
    limit: 2,
    statusCodes: [429, 503],
  },
});

const users = await client.get('/users');

console.log(await users.json());

const created = await client.post(
  '/users',
  JSON.stringify({ email: 'user@example.com' }),
  {
    headers: {
      'content-type': 'application/json',
    },
  }
);

console.log(created.status);

// Optional for long-lived processes; pooled resources are also released after GC.
client.close();

extend a client

const base = createClient({
  baseURL: 'https://api.example.com',
  browser: 'chrome_149',
});

const admin = base.extend({
  headers: {
    authorization: `Bearer ${process.env.ADMIN_TOKEN}`,
  },
});

await base.get('/health');
await admin.get('/admin/stats');

🎭 browser profiles   ·   ↑

Inspect the available profiles at runtime:

import { getProfiles } from 'node-wreq';

console.log(getProfiles());

There is also BROWSER_PROFILES if you want the generated list directly.

Typical profiles include browser families like:

  • Chrome
  • Edge
  • Firefox
  • Safari
  • Opera
  • OkHttp

The current upstream snapshot includes the newest profiles through chrome_149, edge_148, firefox_151, opera_131, and safari_26_4. When browser is omitted, chrome_149 is used.

You can also select a platform explicitly or ask upstream to choose a profile automatically:

await fetch('https://example.com', {
  browser: {
    profile: 'chrome_149',
    platform: 'windows',
    // Optional component switches from upstream's Emulation builder:
    http2: true,
    headers: true,
  },
});

await fetch('https://example.com', {
  browser: { mode: 'random' },
});

await fetch('https://example.com', {
  // Uses current browser-market-share weights and valid browser/platform pairings.
  browser: { mode: 'weighted-random' },
});

Set browser.http2 to false to behave like that browser with HTTP/2 switched off: the request stays on HTTP/1.1, ALPN offers only http/1.1 and the profile's ALPS extension is dropped (http1Only: true does the same). With http2Only, ALPN offers only h2; no browser narrows its ALPN list like that, so it is visible in the TLS fingerprint. Set browser.headers to false to omit the profile's default headers and header ordering; the top-level disableDefaultHeaders option remains a convenient request-wide equivalent for the latter.

🪝 hooks   ·   ↑

Hooks are the request pipeline.

Available phases:

  • init
  • beforeRequest
  • afterResponse
  • beforeRetry
  • beforeError
  • beforeRedirect

common pattern: auth, tracing, proxy rotation

import { createClient } from 'node-wreq';

const client = createClient({
  baseURL: 'https://example.com',
  retry: {
    limit: 2,
    statusCodes: [429, 503],
    backoff: ({ attempt }) => attempt * 250,
  },
  hooks: {
    init: [
      ({ options, state }) => {
        options.query = { ...options.query, source: 'hook-init' };

        state.startedAt = Date.now();
      },
    ],
    beforeRequest: [
      ({ request, options, state }) => {
        request.headers.set('x-trace-id', crypto.randomUUID());
        request.headers.set('authorization', `Bearer ${getAccessToken()}`);

        options.proxy = pickProxy();

        state.lastProxy = options.proxy;
      },
    ],
    beforeRetry: [
      ({ options, attempt, error, state }) => {
        options.proxy = pickProxy(attempt);

        console.log('retrying', {
          attempt,
          proxy: options.proxy,
          previousProxy: state.lastProxy,
          error,
        });
      },
    ],
    beforeError: [
      ({ error, state }) => {
        error.message = `[trace=${String(state.startedAt)}] ${error.message}`;

        return error;
      },
    ],
  },
});

replace a response in afterResponse

import { Response, fetch } from 'node-wreq';

const response = await fetch('https://example.com/account', {
  hooks: {
    afterResponse: [
      async ({ response }) => {
        if (response.status === 401) {
          return new Response(JSON.stringify({ guest: true }), {
            status: 200,
            headers: {
              'content-type': 'application/json',
            },
            url: response.url,
          });
        }
      },
    ],
  },
});

console.log(await response.json());

mutate redirect hops

await fetch('https://example.com/login', {
  hooks: {
    beforeRedirect: [
      ({ request, nextUrl, redirectCount }) => {
        request.headers.set('x-redirect-hop', String(redirectCount));
        request.headers.set('x-next-url', nextUrl);
      },
    ],
  },
});

Rule of thumb:

  • use hooks for dynamic behavior
  • use client defaults for static behavior

🍪 cookies and sessions   ·   ↑

node-wreq does not force a built-in cookie store.

You provide a cookieJar with two methods:

  • getCookies(url)
  • setCookie(cookie, url)

That jar can be:

  • in-memory
  • tough-cookie
  • Redis-backed
  • DB-backed
  • anything else that matches the interface

The jar decides which cookies are sent; the native transport decides how they are written. Over HTTP/1.1 they go out as one Cookie: a=1; b=2 header. Over HTTP/2 each pair is sent as its own cookie field, the way browsers do it. A Cookie header you set by hand is treated the same way.

A Cookie header you set by hand is combined with the jar's cookies into one header, rebuilt for every attempt and redirect hop:

  • jar cookies come first, then your own pairs
  • if both have a cookie with the same name, the jar's value is sent (so a cookie the server just updated wins over a stale hand-written one)
  • your own cookie follows same-origin redirects and is dropped from the first cross-origin hop onwards (as authorization is); jar cookies are looked up again for every hop's URL

tiny in-memory jar

import { fetch, websocket } from 'node-wreq';

const jarStore = new Map<string, string>();

const cookieJar = {
  getCookies() {
    return [...jarStore.entries()].map(([name, value]) => ({
      name,
      value,
    }));
  },
  setCookie(cookie: string) {
    const [pair] = cookie.split(';');
    const [name, value = ''] = pair.split('=');

    jarStore.set(name, value);
  },
};

await fetch('https://example.com/login', { cookieJar });
await fetch('https://example.com/profile', { cookieJar });
await websocket('wss://example.com/ws', { cookieJar });

tough-cookie

npm install tough-cookie
import { CookieJar as ToughCookieJar } from 'tough-cookie';
import { createClient } from 'node-wreq';

const toughJar = new ToughCookieJar();

const cookieJar = {
  async getCookies(url: string) {
    const cookies = await toughJar.getCookies(url);

    return cookies.map((cookie) => ({
      name: cookie.key,
      value: cookie.value,
    }));
  },
  async setCookie(cookie: string, url: string) {
    await toughJar.setCookie(cookie, url);
  },
};

const client = createClient({
  browser: 'chrome_149',
  cookieJar,
});

await client.fetch('https://example.com/login');
await client.fetch('https://example.com/profile');

inspect cookies on a response

import { fetch } from 'node-wreq';

const response = await fetch('https://example.com/login', { cookieJar });

console.log(response.wreq.setCookies);
console.log(response.wreq.cookies);

🔁 redirects and retries   ·   ↑

Both are opt-in controls on top of the normal request pipeline.

manual redirects

const response = await fetch('https://example.com/login', {
  redirect: 'manual',
});

console.log(response.status);
console.log(response.headers.get('location'));
console.log(response.redirected);

Modes:

  • follow - default redirect following
  • manual - return the redirect response as-is
  • error - throw on the first redirect

Useful redirect facts:

  • response.wreq.redirectChain records followed hops
  • 301 / 302 rewrite POST to GET
  • 303 rewrites to GET unless current method is HEAD
  • 307 / 308 preserve method and body
  • at most maxRedirects hops are followed (default 20), then the request rejects with ERR_TOO_MANY_REDIRECTS
  • there is no loop detection, as in browsers and the Fetch standard: a redirect may go back to a URL it already visited (e.g. "set a cookie and redirect back"), and an endless loop ends at the maxRedirects limit
  • authorization, cookie and proxy-authorization are removed on cross-origin hops (a cookieJar still supplies its own cookies for the new URL)

simple retries

const response = await fetch('https://example.com', {
  retry: 2,
});

explicit retry policy

const response = await fetch('https://example.com', {
  retry: {
    limit: 3,
    statusCodes: [429, 503],
    backoff: ({ attempt }) => attempt * 500,
  },
});

custom retry decision

import { TimeoutError, fetch } from 'node-wreq';

const response = await fetch('https://example.com', {
  retry: {
    limit: 5,
    shouldRetry: ({ error, response }) => {
      if (response?.status === 429) {
        return true;
      }

      return error instanceof TimeoutError;
    },
  },
});

Defaults:

  • retry is off unless you enable it
  • default retry methods are GET and HEAD (methods is matched case-insensitively)
  • default status codes are 408, 425, 429, 500, 502, 503, 504
  • default error codes are ECONNABORTED, ECONNRESET, ECONNREFUSED, EPIPE, ETIMEDOUT, ERR_TIMEOUT

How a retry is decided and timed:

  • an abort (your signal, including AbortSignal.timeout()) is never retried, even if ERR_ABORTED is in errorCodes; aborting while waiting for a backoff rejects right away
  • a request whose body is a ReadableStream or (async) iterable is not retried once the body has been sent, since it cannot be read again; you get the original response or error instead
  • shouldRetry runs once per failed attempt and only after the checks above (attempts left, method, status / error code) passed: it can veto a retry, not add one. Widen statusCodes, errorCodes or methods to retry more
  • there is no default delay: without backoff, retries happen immediately. Retry-After is not applied automatically; read it in backoff if you want it, and cap it yourself:
const response = await fetch('https://example.com', {
  retry: {
    limit: 3,
    backoff: ({ attempt, response }) => {
      const retryAfter = Number(response?.headers.get('retry-after'));

      return Number.isFinite(retryAfter)
        ? Math.min(retryAfter * 1000, 30_000)
        : 2 ** attempt * 250;
    },
  },
});

📊 observability   ·   ↑

Two main surfaces:

  • response.wreq.timings
  • onStats(stats)

per-request stats callback

await fetch('https://example.com', {
  onStats: ({ attempt, timings, response, error }) => {
    console.log({
      attempt,
      wait: timings.wait,
      total: timings.total,
      status: response?.status,
      error,
    });
  },
});

read timings from the final response

const response = await fetch('https://example.com', {
  browser: 'chrome_149',
});

console.log(response.wreq.timings);

Current timings are wrapper-level timings that are still useful in practice:

  • request start
  • response available
  • total time when body consumption is known

🚨 error handling   ·   ↑

Main error classes:

  • RequestError
  • HTTPError
  • TimeoutError
  • AbortError
  • WebSocketError

Every error carries a machine-readable code when one is available, for example ERR_TIMEOUT, ERR_HTTP_STATUS, or ERR_DNS for failed hostname lookups.

Typical patterns:

import { HTTPError, TimeoutError, fetch } from 'node-wreq';

try {
  await fetch('https://example.com', {
    timeout: 1_000,
    throwHttpErrors: true,
  });
} catch (error) {
  if (error instanceof TimeoutError) {
    console.error('request timed out');
  } else if (error instanceof HTTPError) {
    console.error('bad status', error.status);
  } else {
    console.error(error);
  }
}

🔌 websockets   ·   ↑

You can use either:

  • await websocket(url, init?)
  • new WebSocket(url, init?)

simple helper

import { websocket } from 'node-wreq';

const socket = await websocket('wss://echo.websocket.events', {
  browser: 'chrome_149',
  protocols: ['chat'],
});

socket.addEventListener('message', (event) => {
  console.log('message:', event.data);
});

socket.send('hello');

WHATWG-like constructor

import { WebSocket } from 'node-wreq';

const socket = new WebSocket('wss://example.com/ws', {
  binaryType: 'arraybuffer',
});

await socket.opened;

socket.onmessage = (event) => {
  if (event.data instanceof ArrayBuffer) {
    console.log(new Uint8Array(event.data));
  }
};

socket.send(new Uint8Array([1, 2, 3]));
socket.close(1000, 'done');

websocket from a client

Useful when you want shared defaults like browser, proxy, or cookies:

const client = createClient({
  browser: 'chrome_149',
  cookieJar: yourCookieJar,
});

const socket = await client.websocket('wss://example.com/ws');

Notes:

  • cookies from cookieJar are sent during handshake, and Set-Cookie headers on the handshake response are stored back into it before open fires
  • the opening handshake fails after timeout ms (default 240000), and close() waits closeTimeout ms (default 60000, both as in Chromium) for the server's close frame; after that the connection is dropped and close fires with code 1006 and wasClean: false
  • received messages are buffered natively only up to a small bound; if your code stops the event loop, the socket stops being read instead of growing memory
  • a socket you stop referencing is closed once it is garbage collected, unless it still has message, error or close listeners (as in browsers); call close() when you are done
  • duplicate subprotocols are rejected
  • httpVersion: '1.1' | '2' explicitly selects the handshake HTTP version
  • the handshake is not a page navigation, so it does not carry the profile's navigation headers (accept, sec-fetch-*, upgrade-insecure-requests, client hints, priority). With Chromium-family profiles it is laid out like Chrome's: Host, Connection, Pragma, Cache-Control, User-Agent, Upgrade, Origin, Sec-WebSocket-Version, Accept-Encoding, Accept-Language, Cookie, your other headers, then Sec-WebSocket-Key and Sec-WebSocket-Protocol. Origin is only sent when you pass one. Other profiles keep their headers minus sec-fetch-user and upgrade-insecure-requests. disableDefaultHeaders: true sends only your headers, in your order
  • unlike a browser, the handshake does not offer permessage-deflate, and wreq sends Connection: upgrade in lowercase

🧪 networking / transport knobs   ·   ↑

This is the "transport nerd" section.

Everything else here is for debugging request shape, fingerprint-sensitive targets, or testing transport hypotheses.

browser profile + proxy + timeout

const response = await fetch('https://httpbin.org/anything', {
  browser: 'chrome_149',
  proxy: 'http://username:password@proxy.example.com:8080',
  timeout: 10_000,
});

Timeouts:

  • there is no time limit by default, as in browsers and the Fetch standard: a request waits as long as the connection stays alive. Pass signal: AbortSignal.timeout(ms) or timeout
  • timeout is the total budget for one attempt. It runs from the start of the request until the response body has been read completely, so it also cuts off slow downloads, streamed bodies and SSE / long-polling responses: reading the body fails once it expires. Each retry and each redirect hop starts a fresh budget
  • readTimeout is the longest the response may stay idle between chunks, which suits long-lived streams; connectTimeout limits connection setup. Both are off unless set
const events = await fetch('https://example.com/events', {
  connectTimeout: 10_000,
  readTimeout: 60_000,
});

If you want to bypass env/system proxy detection for a specific request, use proxy: false:

await fetch('https://example.com', {
  proxy: false,
});

disable default browser-like headers

By default, node-wreq may apply profile-appropriate default headers.

disableDefaultHeaders: true disables those browser/profile preset headers only.

That means it turns off headers injected by the selected browser emulation, such as:

  • user-agent
  • accept
  • accept-language
  • sec-ch-ua
  • sec-ch-ua-mobile
  • sec-ch-ua-platform
  • sec-fetch-dest
  • sec-fetch-mode
  • sec-fetch-site
  • priority

The exact set varies by profile.

It does not disable protocol or transport-level headers that may still appear automatically, such as:

  • host
  • accept-encoding when compress is enabled
  • content-length when the request body requires it
  • content-type generated by the runtime for bodies like FormData

It also does not remove headers you set explicitly yourself.

If you want full manual control:

await fetch('https://example.com', {
  disableDefaultHeaders: true,
  headers: {
    accept: '*/*',
    'user-agent': 'custom-client',
  },
});

For example, with browser: 'chrome_149', the default request would normally include Chrome-like sec-ch-*, sec-fetch-*, user-agent, accept, and accept-language headers. With disableDefaultHeaders: true, those browser preset headers are skipped, while transport headers like host and accept-encoding may still be present.

exact header order

Use tuples when header order matters.

Tuple headers also preserve the original header names exactly as you wrote them on the wire:

await fetch('https://example.com', {
  headers: [
    ['x-lower', 'one'],
    ['X-Mixed', 'two'],
  ],
});

For example, this will preserve both the tuple order and the exact x-lower / X-Mixed casing you passed.

While a browser profile's default headers are active, the profile also has a say in the order:

  • headers the profile does not define are sent first (after Host), in the order you gave them
  • headers the profile defines keep the profile's position, even when you override their value, so setting accept-language or user-agent does not move it to the front
  • with Chromium-family profiles, cookie is placed right before priority, where Chromium sends it
  • Host goes first and the profile's headers get the browser's HTTP/1.1 spelling (User-Agent, Sec-Fetch-Mode, …; Chrome's sec-ch-ua* stay lowercase); names you pass keep your spelling. HTTP/2 lowercases every name anyway
  • with Chromium-family profiles, requests that cannot use HTTP/2 (http:// URLs without http2Only, or http1Only) get Chrome's HTTP/1.1 layout: Connection: keep-alive right after Host, and no priority header. Over https:// the protocol is negotiated after the headers are fixed, so those requests keep the HTTP/2 layout even when the server picks HTTP/1.1

To take over the order completely, turn the profile headers off with disableDefaultHeaders: true (or browser: { headers: false }) and pass every header yourself.

lower-level transport tuning

If a browser preset gets you close but not all the way there:

await fetch('https://example.com', {
  browser: 'chrome_149',
  tlsOptions: {
    greaseEnabled: true,
    keyShares: ['X25519_MLKEM768', 'X25519', 'P256'],
  },
  http1Options: {
    writev: true,
  },
  http2Options: {
    adaptiveWindow: false,
    maxConcurrentStreams: 64,
  },
});

Use these only when:

  • a target is still picky after choosing a browser profile
  • you are comparing transport behavior
  • you want to debug fingerprint mismatches

Custom TLS/HTTP1/HTTP2 options are overlaid on the selected browser profile. Unspecified profile settings remain intact.

native connection and TLS-session pools

createClient() reuses the underlying native wreq::Client, including HTTP keep-alive connections and TLS sessions. The browser profile, proxy, local address and HTTP version travel with each request, and wreq keeps their connections and TLS sessions apart inside one client: requests through two proxies, or with two profiles, never share a connection, and switching proxies per request does not create new clients. Only options that exist on the native client builder alone (DNS, TLS identity and trust, connectTimeout, tcpLinger, pool limits, the system-proxy switch) get a client variant of their own.

Top-level fetch() calls (and WebSockets opened without a client) do the same through one implicit, process-wide owner: calls with the same options share connections and TLS sessions, the way requests from one browser profile do (cookies are never shared; they live in the cookie jar you pass). In browser: { mode: 'random' } or 'weighted-random' a client picks one profile and keeps it, so each top-level call in those modes gets its own client: it keeps one identity across its redirects and retries while separate calls still draw separate identities. Use a createClient() instance to keep one random identity across calls. Proxy environment variables (HTTP_PROXY, NO_PROXY, ...) are part of the client key, but operating-system proxy settings are read only when a native client is built.

Each owner keeps at most 64 client variants (and 64 resolved profiles) and drops the least recently used one beyond that; requests already running on a dropped variant finish normally.

const client = createClient({
  baseURL: 'https://api.example.com',
  poolIdleTimeout: 90_000,
  poolMaxIdlePerHost: 8,
  poolMaxSize: 128,
  tlsSessionCacheCapacity: 8,
  tcpLinger: 5_000,
});

await client.get('/account', {
  // Requests in different groups never share pooled connections.
  connectionGroup: 'account-session',
});

const response = await client.get('/health', {
  // Static form: discard this request's connection after the response.
  forbidConnectionReuse: true,
});

// Conditional form: call before consuming the body.
response.wreq.forbidConnectionReuse();

client.close();

Set poolIdleTimeout: false to disable idle expiry. connectionGroup accepts a string or a non-negative integer. tcpLinger configures SO_LINGER in milliseconds; 0 requests an abortive close with TCP RST, while omitting the option keeps the operating-system default.

mTLS and custom CAs

Use tlsIdentity for client certificate authentication and ca for a custom trust store:

import { fetch } from 'node-wreq';
import { readFileSync } from 'node:fs';

await fetch('https://mtls.example.com', {
  tlsIdentity: {
    cert: readFileSync('./client-cert.pem'),
    key: readFileSync('./client-key.pem'),
  },
  ca: {
    cert: readFileSync('./ca.pem'),
    includeDefaultRoots: false,
  },
});

PKCS#12 / PFX identities are also supported:

await fetch('https://mtls.example.com', {
  tlsIdentity: {
    pfx: readFileSync('./client-identity.p12'),
    passphrase: 'secret',
  },
  ca: {
    cert: readFileSync('./ca.pem'),
    includeDefaultRoots: false,
  },
});

For TLS diagnostics, you can ask for peer certificate metadata on the response or write TLS session keys to a file for tools like Wireshark:

const response = await fetch('https://mtls.example.com', {
  tlsDebug: {
    peerCertificates: true,
    keylog: {
      path: '/tmp/node-wreq.keys',
    },
  },
});

console.log(response.wreq.tls?.peerCertificate);
console.log(response.wreq.tls?.peerCertificateChain);

Unsafe TLS overrides are separate and explicit:

await fetch('https://staging.internal.example', {
  tlsDanger: {
    certVerification: false,
    verifyHostname: false,
    sni: false,
  },
});

compression

Compression is enabled by default.

That includes gzip, br, deflate, and zstd response decoding when the server supports them.

Disable it if you need stricter control over response handling:

await fetch('https://example.com/archive', {
  compress: false,
});

DNS controls

Use dns.hosts to pin hostnames to specific IPs, or dns.servers to send lookups through specific nameservers:

await fetch('https://api.internal.test/health', {
  dns: {
    servers: ['1.1.1.1', '8.8.8.8'],
    hosts: {
      'api.internal.test': ['127.0.0.1'],
    },
  },
});

Use dns.doh to resolve request hostnames through DNS-over-HTTPS:

await fetch('https://example.com', {
  dns: {
    doh: 'https://cloudflare-dns.com/dns-query',
  },
});

Use dns.dot to resolve request hostnames through DNS-over-TLS:

await fetch('https://example.com', {
  dns: {
    dot: 'tls://one.one.one.one',
  },
});

dns.doh and dns.dot are mutually exclusive. When either encrypted DNS mode is set, dns.servers are used only to resolve the encrypted DNS endpoint hostname. If dns.servers are omitted, the endpoint is resolved with the system DNS settings.

await fetch('https://example.com', {
  dns: {
    doh: 'https://cloudflare-dns.com/dns-query',
    servers: ['9.9.9.9'],
  },
});