Skip to main content
Version: 3

HTTP clients

The Apify API client uses a pluggable HTTP layer. It ships with a default built on the fetch of the runtime and an opt-in client built on axios, and it accepts custom implementations.

Default HTTP client

When you create an ApifyClient, it sends its requests through the built-in FetchHttpClient. It uses the global fetch, so it works the same way in Node.js, browsers and edge runtimes and adds no dependency. This default client provides:

  • Automatic retries with exponential backoff for network errors, HTTP 429 and HTTP 5xx responses.
  • Configurable timeout tiers that grow with every retry.
  • Request compression and preparation of API-compatible bodies, query parameters and headers, including authentication.
  • Keep-alive connections, which fetch manages on its own.
  • API error handling and request statistics.

You configure the default client through the ApifyClient constructor:

import { ApifyClient } from 'apify-client';

const client = new ApifyClient({
token: 'MY-APIFY-TOKEN',
maxRetries: 4,
minDelayBetweenRetriesMillis: 500,
timeoutMediumSecs: 60,
headers: { 'x-apify-integration-platform': 'my-platform' },
});

Anything beyond those options is configured on a FetchHttpClient instance that you plug in yourself. Its fetch option takes the function the requests go through: a wrapper around the global fetch for a header computed per request, or the fetch of another library. A stream body reaches that function as an async iterable of byte chunks, or in a browser or an edge runtime as a web ReadableStream when it was passed as one. Retries, timeouts and compression then live on the HTTP client too:

import { ApifyClient, FetchHttpClient } from 'apify-client';

const httpClient = new FetchHttpClient({
maxRetries: 4,
// Runs for every attempt, with the request as the shared pipeline prepared it.
fetch: async (input, init) => {
const headers = new Headers(init?.headers);
headers.set('X-Request-Id', crypto.randomUUID());
return fetch(input, { ...init, headers });
},
});

const client = ApifyClient.withCustomHttpClient({ token: 'MY-APIFY-TOKEN', httpClient });

The timeout of a request runs until the response headers arrive and starts over with every chunk of the response body, so a large download doesn't time out while it makes progress. In Node.js, the same goes for an upload whose body is a stream or a Blob. Any other body has to be sent within the timeout.

In Node.js, fetch closes a connection that has been idle for about 4 seconds, unless the server asks for a longer time, so a request that follows a longer pause opens a new one. The axios client keeps an idle connection until the server closes it. To keep connections of the default client open longer, pass a fetch that goes through an undici Agent with a longer keepAliveTimeout:

import { ApifyClient, FetchHttpClient } from 'apify-client';
import { Agent, fetch as undiciFetch } from 'undici';

const dispatcher = new Agent({ keepAliveTimeout: 60_000 });
const httpClient = new FetchHttpClient({
fetch: (input, init) => undiciFetch(input, { ...init, dispatcher }),
});

const client = ApifyClient.withCustomHttpClient({ token: 'MY-APIFY-TOKEN', httpClient });

Axios HTTP client

Up to version 2, the client sent its requests through axios. That transport is still available as AxiosHttpClient, for code that depends on axios behavior such as request interceptors or http.Agent instances. It has an entry point of its own, apify-client/axios, and axios is an optional peer dependency, so install it next to the client:

npm install axios
import { ApifyClient } from 'apify-client';
import { AxiosHttpClient } from 'apify-client/axios';

const httpClient = new AxiosHttpClient({
maxRetries: 4,
requestInterceptors: [
(config) => {
config.headers.set('X-Request-Id', crypto.randomUUID());
return config;
},
],
});

const client = ApifyClient.withCustomHttpClient({ token: 'MY-APIFY-TOKEN', httpClient });

In Node.js, it creates keep-alive agents with its first request, or uses the ones you pass in the httpAgent and httpsAgent options. The entry point is meant for Node.js. It isn't part of the pre-built browser bundle, and an ApifyClient imported from that bundle rejects an AxiosHttpClient.

Proxies

The client doesn't route requests through a proxy on its own. How to set one up depends on the HTTP client and the runtime:

  • Default client on Node.js 22.21 or 24 and newer - Start Node.js with NODE_USE_ENV_PROXY=1. The --use-env-proxy flag does the same on Node.js 22.21 and on 24.5 and newer. Its fetch then reads the HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment variables.
  • Default client on Node.js 24.14 and newer, from inside the application - Call http.setGlobalProxyFromEnv() before the first request. It has the same effect as the switch, for a tool that can't control how Node.js is started.
  • Default client on an older Node.js, or a proxy for this client only - Pass a fetch that goes through a proxy, such as the one of undici with a dispatcher.
  • Axios client - Pass a proxy agent, such as one from proxy-agent, in the httpAgent and httpsAgent options.
  • Browsers, Bun and Deno - The runtime applies its own proxy settings, so there is nothing to configure.
NODE_USE_ENV_PROXY=1 HTTPS_PROXY=http://proxy.example.com:3128 node main.js
import { ApifyClient, FetchHttpClient } from 'apify-client';
import { EnvHttpProxyAgent, fetch as undiciFetch } from 'undici';

const dispatcher = new EnvHttpProxyAgent();
const httpClient = new FetchHttpClient({
fetch: (input, init) => undiciFetch(input, { ...init, dispatcher }),
});

const client = ApifyClient.withCustomHttpClient({ token: 'MY-APIFY-TOKEN', httpClient });

When a request of the default client fails to connect while a proxy variable is set and Node.js isn't reading it, the client logs a warning that names the variable and the switch to turn on. On a Node.js version that can't route fetch through a proxy, the warning says so.

Architecture

The HTTP client hierarchy has two layers:

  • HttpClient is the abstract base. It holds the shared request pipeline: header merging, body serialization and compression, query encoding, the retry loop, timeout growth, response body parsing, statistics and the conversion of error statuses to ApifyApiError. It declares the transport hooks a concrete client implements.
  • FetchHttpClient and AxiosHttpClient extend it and adapt fetch and axios as the transport.

A custom client extends HttpClient the same way. It implements the transport hook and inherits everything else, so its requests get the same retries, timeouts, compression and error handling as the built-in client.

The HTTP clients and the request and response types are exported from the package root, except for the axios-based client:

import { FetchHttpClient, HttpClient } from 'apify-client';
import type { HttpRequest, HttpResponse } from 'apify-client';
// The axios-based client has an entry point of its own, so that only its users need axios.
import { AxiosHttpClient } from 'apify-client/axios';

HttpClient.isTimeoutError(error) is the transport-neutral way to tell whether an error is a timeout, so code built on the client doesn't need to know which transport threw it.

The transport contract

The public call() method provides the shared request pipeline. A concrete transport implements these hooks:

  • sendRequest(request) sends one prepared request and returns its response, error statuses included. It receives an HttpRequest: the URL with the query string already encoded into it, the headers with the client's default headers already merged in, the body already serialized and compressed, the timeout for this attempt in milliseconds (undefined for a request that runs without one), whether the caller wants the response body as a stream, and the caller's AbortSignal when the call passed one. The inherited call() needs it, so every transport has to implement it. Let the HTTP library's errors propagate unwrapped, and leave status handling and ApifyApiError to call(). Reject when the connection drops before the body is complete. call() doesn't retry a returned body that fails to parse.
  • isRetryableTransportError(error) classifies transport failures for the shared retry loop. The default classifies nothing as retryable, so a transport that doesn't override it gives up on the first connection failure.
  • isTimeoutError(error) identifies the transport's timeout errors. The default recognizes errors named TimeoutError, which is what AbortSignal.timeout() produces. Timeout classification is independent of retryability, so a timeout the retry loop should retry has to be covered by isRetryableTransportError() too.
  • close() releases resources owned by the transport, such as a connection pool. The default does nothing.

Mark your implementations with the override keyword, as the built-in clients do, so the TypeScript compiler catches a misspelled hook.

Request and response shapes

sendRequest() receives an HttpRequest:

FieldDescription
method: HttpMethodHTTP method, for example GET or POST
url: stringFull URL, query string included
headers: Record<string, string>Final request headers
body?: string | Buffer | ArrayBuffer | ArrayBufferView | Readable | ReadableStream | BlobSerialized and compressed body, or undefined. A Blob body arrives in Node.js as a new Readable for every attempt. A web ReadableStream body arrives in Node.js as a Readable too, and as the stream itself elsewhere
timeoutMillis?: numberTimeout of this attempt, or undefined for a request that runs without one
stream: booleanWhether to return the body unread, as a stream. The caller always gets a web ReadableStream
followRedirects: booleanWhether to follow redirects. When it's false, return a redirect response as it is, since the request carries the API token
signal?: AbortSignalThe caller's abort signal, to end the request in flight with. The pipeline stops retrying once it aborts

It returns an HttpResponse. It is an interface, not a class, so any object of this shape will do:

FieldDescription
status: numberHTTP status code
headers: Record<string, string | string[] | undefined>Response headers keyed by lowercase name
body: Uint8Array | ArrayBuffer | Readable | ReadableStream | undefinedRaw body, a stream for a streamed response, or undefined. A Readable is accepted too and converted to a web ReadableStream

The pipeline decodes the body by its content type for the resource clients, so the transport returns raw bytes. They can be a Buffer, any other Uint8Array or an ArrayBuffer, and the pipeline hands them on as a Uint8Array. For a streamed response, return the body unread and let the caller consume it. The callers get a web ReadableStream, so the pipeline converts a Readable that a Node.js transport returns.

Plugging it in

Use ApifyClient.withCustomHttpClient() to create a client with your implementation. The token you pass is set as the HTTP client's Authorization header, unless the client already has one configured:

import { ApifyClient, HttpClient } from 'apify-client';
import type { HttpRequest, HttpResponse } from 'apify-client';

class MyHttpClient extends HttpClient {
override async sendRequest(request: HttpRequest): Promise<HttpResponse> {
// Send the request with the HTTP library of your choice.
throw new Error('Not implemented');
}

override isRetryableTransportError(error: unknown): boolean {
// List the transport's transient failures here, such as its timeout and connection errors.
// Returning false for everything opts out of transport retries entirely.
return this.isTimeoutError(error);
}
}

const client = ApifyClient.withCustomHttpClient({
token: 'MY-APIFY-TOKEN',
httpClient: new MyHttpClient(),
});

After that, all API calls made through the client go through your HTTP client.

warning

If you override call() itself, your implementation becomes responsible for request preparation, retries, timeouts, API error conversion and statistics. It also has to send the client's default headers with every request, otherwise the Authorization header never reaches the API, and to honor the per-request compression, authorizationHeader, throwOnErrorStatus, retryStatusCodes, retryTransportErrors and followRedirects options of ApifyRequestConfig. ActorServerClient.request() relies on them to keep the API token away from the Actor's code, to return the server's error responses and to avoid sending a request to the Actor twice. Implementing the transport hooks and inheriting call() keeps the shared behavior.

Use cases

Custom HTTP clients might be useful when the built-in clients don't cover your requirements, for example when you need to:

  • Use a different HTTP library - Integrate undici, got, or another transport.
  • Route through a proxy - Add request routing that the options under Proxies can't express.
  • Implement custom retry logic - Use different backoff strategies or retry conditions.
  • Log requests and responses - Track API calls for debugging or auditing.
  • Modify requests - Add custom fields, modify the body, or change headers.
  • Collect custom metrics - Measure request latency, track error rates, or count API calls.

For a complete implementation, a compact version of the built-in one, see Build a custom HTTP client. The HttpClient API reference documents the full contract.