# abstractHttpClient<!-- -->

Base class for the HTTP clients used by [ApifyClient](https://docs.apify.com/api/client/js/reference/class/ApifyClient.md).

It holds the shared request pipeline: call merges the default headers in, serializes and compresses the body, encodes the query parameters, retries transient failures with exponential backoff, grows the timeout with every attempt, decodes the response body by content type, records statistics and converts error statuses to [ApifyApiError](https://docs.apify.com/api/client/js/reference/class/ApifyApiError.md). A concrete client only has to implement sendRequest, the transport that moves one prepared request over the wire, and can override the classification and lifecycle hooks isTimeoutError, isRetryableTransportError and close.

Overriding call itself is also supported and bypasses the transport hooks entirely. Such a client has to send the default headers from `defaultHeaders` with every request, otherwise the `Authorization` header never reaches the API. It also has to honor the per-request options [ApifyRequestConfig.compression](https://docs.apify.com/api/client/js/reference/interface/ApifyRequestConfig.md#compression), [ApifyRequestConfig.authorizationHeader](https://docs.apify.com/api/client/js/reference/interface/ApifyRequestConfig.md#authorizationHeader), [ApifyRequestConfig.throwOnErrorStatus](https://docs.apify.com/api/client/js/reference/interface/ApifyRequestConfig.md#throwOnErrorStatus), [ApifyRequestConfig.retryStatusCodes](https://docs.apify.com/api/client/js/reference/interface/ApifyRequestConfig.md#retryStatusCodes), [ApifyRequestConfig.retryTransportErrors](https://docs.apify.com/api/client/js/reference/interface/ApifyRequestConfig.md#retryTransportErrors) and [ApifyRequestConfig.followRedirects](https://docs.apify.com/api/client/js/reference/interface/ApifyRequestConfig.md#followRedirects). [ActorServerClient.request](https://docs.apify.com/api/client/js/reference/class/ActorServerClient.md#request) relies on them to keep the token away from the Actor's code, to return the server's error responses and to avoid sending a request to the Actor twice. The protected helpers `prepareRequest()`, `buildUrl()` and `computeTimeoutMillis()` stay available to it.

### Hierarchy

* *HttpClient*
  * [FetchHttpClient](https://docs.apify.com/api/client/js/reference/class/FetchHttpClient.md)

```
import { ApifyClient, HttpClient } from 'apify-client';



class MyFetchHttpClient extends HttpClient {

    async sendRequest({ method, url, headers, body, timeoutMillis, followRedirects, signal }) {

        const signals = signal ? [signal] : [];

        if (timeoutMillis !== undefined) signals.push(AbortSignal.timeout(timeoutMillis));

        const response = await fetch(url, {

            method,

            headers,

            body,

            redirect: followRedirects ? 'follow' : 'manual',

            signal: AbortSignal.any(signals),

        });

        return {

            status: response.status,

            headers: Object.fromEntries(response.headers),

            body: await response.arrayBuffer(),

        };

    }



    isRetryableTransportError(error) {

        // Without this the client gives up on the first connection failure.

        return this.isTimeoutError(error) || error instanceof TypeError;

    }

}



const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new MyFetchHttpClient() });
```

## Index[](#Index)

### Constructors

* [constructor](#constructor)

### Properties

* [httpCompressor](#httpCompressor)
* [logger](#logger)
* [maxRetries](#maxRetries)
* [minDelayBetweenRetriesMillis](#minDelayBetweenRetriesMillis)
* [stats](#stats)
* [timeoutMaxMillis](#timeoutMaxMillis)
* [timeoutMillis](#timeoutMillis)

### Methods

* [call](#call)
* [close](#close)
* [isRetryableTransportError](#isRetryableTransportError)
* [isTimeoutError](#isTimeoutError)
* [sendRequest](#sendRequest)
* [setDefaultAuthorization](#setDefaultAuthorization)

## Constructors<!-- -->[](#Constructors)

### [](#constructor)[](https://github.com/apify/apify-client-js/blob/84036425d1fb761bc98185b09045076b3c86192b/src/http_clients/base.ts#L376)constructor

* **new HttpClient**(options): [HttpClient](https://docs.apify.com/api/client/js/reference/class/HttpClient.md)

- ***

  #### Parameters

  * ##### options: [HttpClientOptions](https://docs.apify.com/api/client/js/reference/interface/HttpClientOptions.md) = <!-- -->{}

    Configuration of the pipeline. The retry and timeout options are validated the same way the `ApifyClient` constructor validates them.

  #### Returns [HttpClient](https://docs.apify.com/api/client/js/reference/class/HttpClient.md)

  Throws - When a retry or timeout option is out of bounds.

## Properties<!-- -->[](#Properties)

### [](#httpCompressor)[](https://github.com/apify/apify-client-js/blob/84036425d1fb761bc98185b09045076b3c86192b/src/http_clients/base.ts#L362)readonlyhttpCompressor

httpCompressor: [HttpCompressor](https://docs.apify.com/api/client/js/reference/interface/HttpCompressor.md)

Compressor the request pipeline runs the bodies worth compressing through.

### [](#logger)[](https://github.com/apify/apify-client-js/blob/84036425d1fb761bc98185b09045076b3c86192b/src/http_clients/base.ts#L347)logger

logger: Log

Logger for the retry warnings.

### [](#maxRetries)[](https://github.com/apify/apify-client-js/blob/84036425d1fb761bc98185b09045076b3c86192b/src/http_clients/base.ts#L350)maxRetries

maxRetries: number

How many times a failed request is retried at most.

### [](#minDelayBetweenRetriesMillis)[](https://github.com/apify/apify-client-js/blob/84036425d1fb761bc98185b09045076b3c86192b/src/http_clients/base.ts#L353)minDelayBetweenRetriesMillis

minDelayBetweenRetriesMillis: number

Lower bound for the delay before the first retry in milliseconds. It doubles with every further retry.

### [](#stats)[](https://github.com/apify/apify-client-js/blob/84036425d1fb761bc98185b09045076b3c86192b/src/http_clients/base.ts#L344)stats

stats: Statistics

Statistics of the API calls made through this client.

### [](#timeoutMaxMillis)[](https://github.com/apify/apify-client-js/blob/84036425d1fb761bc98185b09045076b3c86192b/src/http_clients/base.ts#L359)timeoutMaxMillis

timeoutMaxMillis: number

Upper bound for the timeout of a single attempt, in milliseconds.

### [](#timeoutMillis)[](https://github.com/apify/apify-client-js/blob/84036425d1fb761bc98185b09045076b3c86192b/src/http_clients/base.ts#L356)timeoutMillis

timeoutMillis: Record<[TimeoutTier](https://docs.apify.com/api/client/js/reference.md#TimeoutTier), number>

Duration of each timeout tier, in milliseconds.

## Methods<!-- -->[](#Methods)

### [](#call)[](https://github.com/apify/apify-client-js/blob/84036425d1fb761bc98185b09045076b3c86192b/src/http_clients/base.ts#L488)call

* **call**\<T>(config): Promise<[ApifyResponse](https://docs.apify.com/api/client/js/reference/interface/ApifyResponse.md)\<T>>

- Makes an API request with automatic retries and exponential backoff.

  Network errors the transport classifies as retryable, rate limits (HTTP 429) and server errors (HTTP 5xx) are retried up to maxRetries times, and `config.retryStatusCodes` picks other statuses to retry. Any other error status is thrown as [ApifyApiError](https://docs.apify.com/api/client/js/reference/class/ApifyApiError.md) right away, or returned when `config.throwOnErrorStatus` is `false`. A request whose body is a `Readable` or a web `ReadableStream` is never retried, since part of the stream has already been consumed by the time the failure shows. A `Blob` body is read again for every attempt, so it is retried like any other, unless reading the blob itself fails: that error is thrown right away, with the transport error as its `cause` when that error does not already wrap it. Aborting `config.signal` ends the attempt in flight, skips the remaining retries and rejects the call with the signal's `reason`.

  ***

  #### Parameters

  * ##### config: [ApifyRequestConfig](https://docs.apify.com/api/client/js/reference/interface/ApifyRequestConfig.md)

    The request to make.

  #### Returns Promise<[ApifyResponse](https://docs.apify.com/api/client/js/reference/interface/ApifyResponse.md)\<T>>

  The successful response, or the error response when `config.throwOnErrorStatus` is `false`.

  Throws - When the API responds with an error status the retries could not fix, unless `config.throwOnErrorStatus` is `false`.

### [](#close)[](https://github.com/apify/apify-client-js/blob/84036425d1fb761bc98185b09045076b3c86192b/src/http_clients/base.ts#L447)close

* **close**(): Promise\<void>

- Releases resources owned by the transport, such as a connection pool. The default does nothing.

  ***

  #### Returns Promise\<void>

### [](#isRetryableTransportError)[](https://github.com/apify/apify-client-js/blob/84036425d1fb761bc98185b09045076b3c86192b/src/http_clients/base.ts#L440)isRetryableTransportError

* **isRetryableTransportError**(\_error): boolean

- Whether an error thrown by the transport is worth retrying.

  The default classifies nothing as retryable, so a transport that does not override it gives up on the first connection failure. Every transport should map its own transient errors here: connection resets, refused connections, timeouts and the like. Error responses are not the transport's concern, the pipeline decides on them from the status code.

  ***

  #### Parameters

  * ##### \_error: unknown

  #### Returns boolean

### [](#isTimeoutError)[](https://github.com/apify/apify-client-js/blob/84036425d1fb761bc98185b09045076b3c86192b/src/http_clients/base.ts#L428)isTimeoutError

* **isTimeoutError**(error): boolean

- Whether an error thrown by the transport is a timeout.

  Recognizes errors named `TimeoutError`, which is what `AbortSignal.timeout()` produces. Transports extend it with the timeout errors their HTTP library throws. The classification is independent of retryability: a timeout the retry loop should retry has to be covered by isRetryableTransportError too.

  ***

  #### Parameters

  * ##### error: unknown

  #### Returns boolean

### [](#sendRequest)[](https://github.com/apify/apify-client-js/blob/84036425d1fb761bc98185b09045076b3c86192b/src/http_clients/base.ts#L464)sendRequest

* **sendRequest**(request): Promise<[HttpResponse](https://docs.apify.com/api/client/js/reference/interface/HttpResponse.md)>

- Sends one prepared request through the underlying HTTP library.

  The inherited call needs it, so every transport has to implement it. Let the library's errors propagate unwrapped: call classifies them through isRetryableTransportError and isTimeoutError. Return error responses as they are too, the pipeline turns them into [ApifyApiError](https://docs.apify.com/api/client/js/reference/class/ApifyApiError.md) and decides whether to retry. Reject when the connection drops before the body is complete: the pipeline takes a returned body as whole and does not retry one that fails to parse. When `request.followRedirects` is `false`, return a redirect response as it is, since the request carries a token.

  ***

  #### Parameters

  * ##### request: [HttpRequest](https://docs.apify.com/api/client/js/reference/interface/HttpRequest.md)

    The request to send, with the headers merged, the body serialized and the query encoded.

  #### Returns Promise<[HttpResponse](https://docs.apify.com/api/client/js/reference/interface/HttpResponse.md)>

  The response, with the body unread when `request.stream` is set and as raw bytes otherwise.

### [](#setDefaultAuthorization)[](https://github.com/apify/apify-client-js/blob/84036425d1fb761bc98185b09045076b3c86192b/src/http_clients/base.ts#L415)setDefaultAuthorization

* **setDefaultAuthorization**(token): void

- Sets the `Authorization` header from the token, unless an authorization header is already configured.

  ***

  #### Parameters

  * ##### token: string

    The Apify API token to send as the `Bearer` token.

  #### Returns void
