# Upgrading to v3

Copy for LLM

This page summarizes the breaking changes when upgrading from v2 to v3 of `apify-client`.

Most projects only need to check these:

* The client needs [Node.js 22.15](#nodejs-2215-or-newer-is-required) and [TypeScript 5.9](#typescript-59-or-newer-is-required), and it ships as [pure ESM](#the-package-is-now-pure-esm).
* Calls to an ID that doesn't exist resolve to `undefined` as before, but some [404s now throw](#a-404-throws-where-it-used-to-resolve-to-undefined).
* The client-wide `timeoutSecs` is replaced by [timeout tiers](#timeouts-are-configured-per-tier), and the run timeout of `start()` and `call()` is renamed to `runTimeoutSecs`.
* The [published types](#published-types-now-follow-the-openapi-specification) follow the OpenAPI specification, so expect new null checks.
* Many model types are [renamed](#model-types-take-the-names-of-the-openapi-schemas) to the names of the OpenAPI schemas they're built on.
* Responses are [validated](#responses-are-validated-against-the-openapi-specification), and a response that doesn't match the specification throws.

## Node.js 22.15 or newer is required[](#nodejs-2215-or-newer-is-required)

The client supports Node.js 22.15 and newer. Node.js 18 and 20 are no longer supported, and `package.json` declares `"engines": { "node": ">=22.15.0" }`.

## TypeScript 5.9 or newer is required[](#typescript-59-or-newer-is-required)

TypeScript 5.9 is the oldest supported version; older versions are not tested. v2 worked with TypeScript 5.1. Plain JavaScript projects are unaffected.

## The package is now pure ESM[](#the-package-is-now-pure-esm)

`apify-client` ships as an ES module. The CommonJS build is gone, along with the `dist/index.mjs` wrapper and the `require` condition in `exports`, so `import` is the supported way to load the client.

```
- const { ApifyClient } = require('apify-client'); // v2

+ import { ApifyClient } from 'apify-client';      // v3
```

A CommonJS project can keep calling `require('apify-client')`: the client has no top-level `await`, and every supported Node.js version loads an ES module through `require()` directly.

A TypeScript project that compiles to CommonJS needs `module` set to `nodenext` or `node20` to import the client. Under `node16`, the import fails with TS1479.

The browser bundle at `dist/bundle.js` is now an ES module instead of UMD, so it no longer defines an `Apify` global. Importing it, whether through a bundler or the `apify-client/browser` subpath, is unchanged. A classic `<script>` tag that read `Apify.ApifyClient` off the global has to become a module script that imports it:

```
- <script src="apify-client/dist/bundle.js"></script>

- <script>const client = new Apify.ApifyClient();</script>

+ <script type="module">

+     import { ApifyClient } from './apify-client/dist/bundle.js';

+     const client = new ApifyClient();

+ </script>
```

For bundler setups, see [Browser bundle](https://docs.apify.com/api/client/js/docs/concepts/bundled-environments.md#browser-bundle).

## Argument validation switched from `ow` to `zod`[](#argument-validation-switched-from-ow-to-zod)

The client now validates the arguments you pass with [zod](https://zod.dev) instead of `ow`. This changes what gets thrown for invalid arguments, and tightens a few gaps `ow` used to let through silently.

### A new error type[](#a-new-error-type)

Invalid arguments now throw an [`ArgumentValidationError`](https://docs.apify.com/api/client/js/reference/class/ArgumentValidationError.md) (exported from `apify-client`), not `ow`'s `ArgumentError`. The message is worded differently, and names the options type the field belongs to:

```
- Expected property `limit` to be of type `number` but received type `string` in object `options`        // v2 (ow)

+ Invalid input: expected number, received the string `ten` at `limit` in `DatasetClientListItemOptions`  // v3 (zod)
```

The structured zod issues are available on `issues`, and the original `ZodError` on `cause`:

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



const client = new ApifyClient({ token: 'MY-APIFY-TOKEN' });



try {

    await client.dataset('my-dataset').listItems({ limit: 'ten' });

} catch (error) {

    if (error instanceof ArgumentValidationError) {

        console.log(error.message); // Invalid input: expected number, received the string `ten` at `limit` in `DatasetClientListItemOptions`

        console.log(error.issues); // [{ code: 'invalid_type', expected: 'number', path: ['limit'], ... }]

    }

}
```

If you were matching on `ow`'s `ArgumentError`, switch to `ArgumentValidationError`. If you were parsing the old message text, use `issues` instead.

### Arrays and functions no longer pass where a plain object is expected[](#arrays-and-functions-no-longer-pass-where-a-plain-object-is-expected)

`ow`'s object check let arrays and functions through wherever a plain object was expected. Zod's does not, so passing one now throws instead of reaching the API with a nonsensical body. This affects `update()` / `create()` fields, `TaskClient.start()` / `call()` input, the storage `schema` option, `DatasetClient.pushItems()` items, and `RequestQueueClient.addRequest()` / `batchAddRequests()` requests.

```
// Now throws: Invalid input: expected an object, received array

await client.actor('my-actor').update([{ name: 'my-actor' }]);
```

`Date`, `Map`, `Set` and other class instances still pass as objects, same as under `ow`.

### `pushItems()` no longer takes an array of strings[](#pushitems-no-longer-takes-an-array-of-strings)

[`DatasetClient.pushItems()`](https://docs.apify.com/api/client/js/reference/class/DatasetClient.md#pushItems) takes an object, an array of objects, or a string holding either one as JSON. v2 also typed and accepted an array of strings, which the API always rejected, so passing one now fails at compile time and throws an `ArgumentValidationError` before any request is sent. Parse the strings into objects first.

### `unwind` takes an array only[](#unwind-takes-an-array-only)

The `unwind` option of [`listItems()`](https://docs.apify.com/api/client/js/reference/class/DatasetClient.md#listItems), [`downloadItems()`](https://docs.apify.com/api/client/js/reference/class/DatasetClient.md#downloadItems) and [`createItemsPublicUrl()`](https://docs.apify.com/api/client/js/reference/class/DatasetClient.md#createItemsPublicUrl) no longer accepts a single string. Passing one fails at compile time and throws an `ArgumentValidationError`. Wrap the field name in an array: `unwind: ['field']`.

### `Infinity` and invalid `Date`s are now rejected[](#infinity-and-invalid-dates-are-now-rejected)

`ow` only checked the type, so `Infinity` passed as a number and an invalid `Date` passed as a date. Zod additionally requires a *finite* number and a *valid* date, so both now throw:

```
// Now throws: Invalid input: expected a finite number at `runTimeoutSecs`, got `Infinity` in `ActorCallOptions`

await client.actor('my-actor').call(undefined, { runTimeoutSecs: Infinity });



// Now throws: Invalid input: expected a valid date at `startedBefore` in `RunCollectionListOptions`

//             Invalid input: expected string, received Date at `startedBefore` in `RunCollectionListOptions`

await client.actor('my-actor').runs().list({ startedBefore: new Date('nonsense') });
```

The second example reports a line per arm, because `startedBefore` accepts either a `Date` or a string.

This affects numeric options such as `waitSecs`, `runTimeoutSecs` and `memory`, and date options such as `startedBefore` / `startedAfter`. `KeyValueStoreClient.setRecord()` now rejects `Infinity` as a record value too, since `JSON.stringify()` turns it into `null`. `NaN` was already rejected in v2.

### A few always-rejected options are gone from the types[](#a-few-always-rejected-options-are-gone-from-the-types)

Some options were declared in the TypeScript types but always rejected by the client's own validation before a request was ever sent: `chunkSize` on `DatasetClient.downloadItems()` and `createItemsPublicUrl()`, and `signature` on `createItemsPublicUrl()` and `createKeysPublicUrl()`. These are no longer part of the option types, so passing them is now a compile-time error instead of a runtime throw.

The reverse also happened: `chunkSize` now works on every `list()` method that takes pagination options. In v2 only `DatasetClient.listItems()` accepted it - everywhere else it type-checked and then threw.

## API errors are thrown as subclasses of `ApifyApiError`[](#api-errors-are-thrown-as-subclasses-of-apifyapierror)

An error response from the API now throws the [`ApifyApiError`](https://docs.apify.com/api/client/js/reference/class/ApifyApiError.md) subclass matching its HTTP status code: [`InvalidRequestError`](https://docs.apify.com/api/client/js/reference/class/InvalidRequestError.md) (400), [`UnauthorizedError`](https://docs.apify.com/api/client/js/reference/class/UnauthorizedError.md) (401), [`ForbiddenError`](https://docs.apify.com/api/client/js/reference/class/ForbiddenError.md) (403), [`NotFoundError`](https://docs.apify.com/api/client/js/reference/class/NotFoundError.md) (404), [`ConflictError`](https://docs.apify.com/api/client/js/reference/class/ConflictError.md) (409), [`RateLimitError`](https://docs.apify.com/api/client/js/reference/class/RateLimitError.md) (429) or [`ServerError`](https://docs.apify.com/api/client/js/reference/class/ServerError.md) (5xx). Any other status code still throws a plain `ApifyApiError`. Every subclass extends `ApifyApiError`, so existing `instanceof ApifyApiError` checks keep working. For details, see [Error subclasses](https://docs.apify.com/api/client/js/docs/concepts/error-handling.md#error-subclasses).

As a result, `error.name`, and with it the first line of the printed stack, now carries the subclass name, such as `NotFoundError: Actor task was not found` instead of `ApifyApiError: Actor task was not found`. Log tooling that matches on the `ApifyApiError` name has to match the subclass names as well.

## A 404 throws where it used to resolve to `undefined`[](#a-404-throws-where-it-used-to-resolve-to-undefined)

Fetching a resource by ID still resolves to `undefined` when the API answers 404, and `delete()` on such a client still resolves without error. These methods now swallow every 404, whatever its `type`. In v2 they swallowed only the `record-not-found` and `record-or-token-not-found` types, and any 404 to a `HEAD` request, and threw for any other 404. The same helper backs [`waitForFinish()`](https://docs.apify.com/api/client/js/reference/class/RunClient.md#waitForFinish) and [`call()`](https://docs.apify.com/api/client/js/reference/class/ActorClient.md#call), which read a swallowed 404 as "the run is not visible yet". They keep polling a run that answers 404 for up to 3 seconds to ride out replica lag, then throw a [`NotFoundError`](https://docs.apify.com/api/client/js/reference/class/NotFoundError.md). A successful poll restarts that window. In v2 they polled a missing run until `waitSecs` ran out, which by default is more than 10 days.

The other change affects endpoints where a 404 can't be pinned to one resource: the missing thing may be the parent or the sub-resource, and the response doesn't say which. Those now throw an [`ApifyApiError`](https://docs.apify.com/api/client/js/reference/class/ApifyApiError.md) with `statusCode` 404 instead of hiding the cause behind `undefined`.

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



const client = new ApifyClient({ token: 'MY-APIFY-TOKEN' });



// v2: resolved to undefined on 404. v3: throws.

let dataset;

try {

    dataset = await client.run('run-id').dataset().get();

} catch (error) {

    if (!(error instanceof ApifyApiError) || error.statusCode !== 404) throw error;

}
```

Affected calls:

* Clients chained off a run or build without an ID: `run.dataset()`, `run.keyValueStore()`, `run.requestQueue()`, `run.log()` and `build.log()`. Their `get()` and `delete()` throw on a 404, and so does `log().get()`. `client.log(id).get()` keeps resolving to `undefined`.
* Singleton endpoints at a fixed path under a resource: [`DatasetClient.getStatistics()`](https://docs.apify.com/api/client/js/reference/class/DatasetClient.md#getStatistics), [`UserClient.monthlyUsage()`](https://docs.apify.com/api/client/js/reference/class/UserClient.md#monthlyUsage), [`UserClient.limits()`](https://docs.apify.com/api/client/js/reference/class/UserClient.md#limits), [`ScheduleClient.getLog()`](https://docs.apify.com/api/client/js/reference/class/ScheduleClient.md#getLog), [`TaskClient.getInput()`](https://docs.apify.com/api/client/js/reference/class/TaskClient.md#getInput) and [`WebhookClient.test()`](https://docs.apify.com/api/client/js/reference/class/WebhookClient.md#test). A 404 there means the parent resource is gone, so these throw as well, and their return types drop `| undefined`.

Lookups by key keep the old behavior, because there the 404 is about the record itself: [`KeyValueStoreClient.getRecord()`](https://docs.apify.com/api/client/js/reference/class/KeyValueStoreClient.md#getRecord) and [`RequestQueueClient.getRequest()`](https://docs.apify.com/api/client/js/reference/class/RequestQueueClient.md#getRequest) still resolve to `undefined`, and [`KeyValueStoreClient.recordExists()`](https://docs.apify.com/api/client/js/reference/class/KeyValueStoreClient.md#recordExists) still answers `false`. `get()` on [`ActorClient.lastRun()`](https://docs.apify.com/api/client/js/reference/class/ActorClient.md#lastRun) and [`TaskClient.lastRun()`](https://docs.apify.com/api/client/js/reference/class/TaskClient.md#lastRun) also keeps resolving to `undefined`, where having no run yet is an ordinary outcome.

[`LogClient.stream()`](https://docs.apify.com/api/client/js/reference/class/LogClient.md#stream) follows the same rule as `get()`: `client.log(id).stream()` resolves to `undefined` on a 404, `run.log().stream()` throws.

A [`StreamedLog`](https://docs.apify.com/api/client/js/reference/class/StreamedLog.md) whose run no longer exists logs a warning and stops, the same way it handles any other error it can't recover from while streaming.

### `UserClient.get()` declares the `undefined` it could always return[](#userclientget-declares-the-undefined-it-could-always-return)

[`UserClient.get()`](https://docs.apify.com/api/client/js/reference/class/UserClient.md#get) is typed `Promise<UserPrivateInfo | undefined>`. It addresses a user by ID, so it belongs with the calls that read a 404 as a missing resource, and it already resolved to `undefined` for one. Only its signature said otherwise, which left the `undefined` to surface as a runtime error somewhere further along. Every other `get()` on the client is typed this way, as is `get()` on the [Python client](https://docs.apify.com/api/client/python).

```
- const user = await client.user('some-id').get();

- console.log(user.username);

+ const user = await client.user('some-id').get();

+ console.log(user?.username);
```

### An empty string is no longer accepted as a version number or environment variable name[](#an-empty-string-is-no-longer-accepted-as-a-version-number-or-environment-variable-name)

[`ActorClient.version()`](https://docs.apify.com/api/client/js/reference/class/ActorClient.md#version), [`ActorClient.build()`](https://docs.apify.com/api/client/js/reference/class/ActorClient.md#build) and [`ActorVersionClient.envVar()`](https://docs.apify.com/api/client/js/reference/class/ActorVersionClient.md#envVar) now throw an [`ArgumentValidationError`](https://docs.apify.com/api/client/js/reference/class/ArgumentValidationError.md) for an empty string, which is what every other resource identifier has always done.

An empty identifier used to build the URL of the whole collection instead of one member, so `actor.version('')` read every version of the Actor and a 404 no longer meant a missing version. `actor.build('')` sent an empty version number to the API. Rejecting it up front keeps the 404 rules above unambiguous.

## Identifiers are encoded into the URL path[](#identifiers-are-encoded-into-the-url-path)

Resource IDs, record keys and request IDs are percent-encoded before they go into the URL, so a value can no longer point a request at a different endpoint. `.` and `..` can't be made safe that way, so they throw an [`ArgumentValidationError`](https://docs.apify.com/api/client/js/reference/class/ArgumentValidationError.md). Every `/` in a resource ID now becomes `~`, where v2 replaced only the first one.

## Published types now follow the OpenAPI specification[](#published-types-now-follow-the-openapi-specification)

Every output type the client publishes, such as [`DatasetResource`](https://docs.apify.com/api/client/js/reference/interface/DatasetResource.md), [`KeyValueStoreResource`](https://docs.apify.com/api/client/js/reference/interface/KeyValueStoreResource.md), [`Build`](https://docs.apify.com/api/client/js/reference/interface/Build.md), [`Run`](https://docs.apify.com/api/client/js/reference/interface/Run.md), [`WebhookResource`](https://docs.apify.com/api/client/js/reference/interface/WebhookResource.md), [`Schedule`](https://docs.apify.com/api/client/js/reference/interface/Schedule.md), [`Task`](https://docs.apify.com/api/client/js/reference/interface/Task.md), [`RequestQueueResource`](https://docs.apify.com/api/client/js/reference/interface/RequestQueueResource.md), and [`UserPrivateInfo`](https://docs.apify.com/api/client/js/reference/interface/UserPrivateInfo.md), is now declared on top of a type generated from the published [OpenAPI specification](https://docs.apify.com/api/v2) instead of being hand-written. Several of the previous hand-written types were wrong, and some even contradicted the client's own runtime behavior. For example, `nextExclusiveStartKey` was typed as a required `string`, but `listKeys()` has always compared it to `null`.

For most consumers, the change only surfaces as new compiler errors. Many fields that were typed as required are now optional (`field?: T`) or nullable (`field: T | null`) to match what the API can actually return. Recompile your project and add the null and undefined checks the compiler points out. These type corrections don't change what the client returns at runtime, only what TypeScript claimed about it before.

A few fields went the other way and became required. `Version.versionNumber` is one, and `Version` is what [`create()`](https://docs.apify.com/api/client/js/reference/class/ActorVersionCollectionClient.md#create) takes, so a call that omitted the version number no longer compiles.

A handful of fields and return types also change entirely to match the client's actual behavior:

* `WebhookResource.lastDispatch` was typed as a `string`, even though the API returns an object. It's now optional and nullable, typed as [`WebhookLastDispatch`](https://docs.apify.com/api/client/js/reference/interface/WebhookLastDispatch.md).
* `Schedule.nextRunAt`, `Schedule.lastRunAt` and `RequestResource.handledAt` were typed as `string`, even though the client has always converted them to `Date`. They're now typed as `Date`, optional and nullable where the API can leave them out. `handledAt` also carries into what [`addRequest()`](https://docs.apify.com/api/client/js/reference/class/RequestQueueClient.md#addRequest), [`batchAddRequests()`](https://docs.apify.com/api/client/js/reference/class/RequestQueueClient.md#batchAddRequests) and [`updateRequest()`](https://docs.apify.com/api/client/js/reference/class/RequestQueueClient.md#updateRequest) take, so a call that marked a request handled with an ISO string has to pass a `Date` instead.
* `Build.status` was typed as the four terminal statuses, even though `waitForFinish()` documents `READY` and `RUNNING`. It's now all eight Actor job statuses, so an exhaustive `switch` over it no longer compiles.
* `WebhookDispatch.webhook` was `Pick<Webhook, 'requestUrl' | 'isAdHoc'>`. It's now an optional, nullable [`WebhookDispatchWebhookSummary`](https://docs.apify.com/api/client/js/reference/interface/WebhookDispatchWebhookSummary.md), which also carries `actionType` and a `condition` typed as the same `WebhookCondition` union `WebhookResource.condition` carries.
* `UserPlan.enabledPlatformFeatures` was a `PlatformFeature[]`, even though the platform has features that enum never gained, such as `PROXY_RESIDENTIAL`. It's now an optional `string[]`. `PlatformFeature` stays published, so an existing comparison against one of its members still works.
* `RequestQueue.expireAt` is gone. The API does not return it on a request queue, so reading it gave `undefined` on every queue you ever fetched.
* [`getRequest()`](https://docs.apify.com/api/client/js/reference/class/RequestQueueClient.md#getRequest) was typed as a queue-head projection, even though the endpoint returns the whole request. It's now the full request schema.
* [`batchDeleteRequests()`](https://docs.apify.com/api/client/js/reference/class/RequestQueueClient.md#batchDeleteRequests) was typed with the batch *add* result, whose processed entries carry `requestId`, `wasAlreadyPresent` and `wasAlreadyHandled`. The delete endpoint answers with none of those, so the return type is now [`BatchDeleteResult`](https://docs.apify.com/api/client/js/reference/interface/BatchDeleteResult.md), whose processed entries carry `id` and `uniqueKey`. Code that read any of the three old fields was reading `undefined`.

A few changes need more than a null check.

### A resource and its list item are no longer interchangeable[](#a-resource-and-its-list-item-are-no-longer-interchangeable)

The specification describes a full resource and its list item as two different shapes, so [`Run`](https://docs.apify.com/api/client/js/reference/interface/Run.md) no longer extends [`RunListItem`](https://docs.apify.com/api/client/js/reference/interface/RunListItem.md), and a [`Build`](https://docs.apify.com/api/client/js/reference/interface/Build.md) still isn't assignable to [`BuildListItem`](https://docs.apify.com/api/client/js/reference/interface/BuildListItem.md), which requires the `usageTotalUsd` that only the list endpoint always returns. Code that passes a full resource where a list item is expected needs to change.

### An Actor version's source files can be folders[](#an-actor-versions-source-files-can-be-folders)

An Actor version's `sourceFiles` is a flat list that mixes files and folders, so its element type is now [`SourceCodeFile`](https://docs.apify.com/api/client/js/reference/interface/SourceCodeFile.md) or the new [`SourceCodeFolder`](https://docs.apify.com/api/client/js/reference/interface/SourceCodeFolder.md). Code that reads `content` or `format` off an element has to tell the two apart first, by the `folder` flag only a folder carries. The `Version` union also gains a fifth variant for `SOURCE_CODE`, [`VersionSourceCode`](https://docs.apify.com/api/client/js/reference/interface/VersionSourceCode.md), so an exhaustive `switch` over `sourceType` no longer compiles.

### Source types and scheduled-action types are plain strings[](#source-types-and-scheduled-action-types-are-plain-strings)

`Version.sourceType` is typed as `'SOURCE_FILES' | 'GIT_REPO' | 'TARBALL' | 'GITHUB_GIST' | 'SOURCE_CODE'` instead of the `ActorSourceType` enum, and a scheduled action's `type` as `'RUN_ACTOR' | 'RUN_ACTOR_TASK'` instead of `ScheduleActions`. Both enums stay published and their members stay assignable, so code that writes `sourceType: ActorSourceType.GitRepo`, or switches over the enum's members, still compiles.

What breaks is reading the value back into a variable or parameter annotated with the enum. `const type: ActorSourceType = version.sourceType` no longer compiles. Annotate it as `Version['sourceType']` instead, or leave it to inference.

The `sortBy` option of `client.actors().list()` and the format argument of [`downloadItems()`](https://docs.apify.com/api/client/js/reference/class/DatasetClient.md#downloadItems) change the same way: they take the values of `ActorListSortBy` and `DownloadItemsFormat` as string literals, and the enums stay published.

### The request-queue head splits into two item types[](#the-request-queue-head-splits-into-two-item-types)

[`RequestResource`](https://docs.apify.com/api/client/js/reference/interface/RequestResource.md) is now derived from the specification's stored-request schema. Its `id`, `url` and `uniqueKey` stay required, as the specification states them, and the rest of the fields follow the specification's optionality.

The queue head splits into two item types. [`listHead()`](https://docs.apify.com/api/client/js/reference/class/RequestQueueClient.md#listHead) still yields [`RequestQueueHeadItem`](https://docs.apify.com/api/client/js/reference/interface/RequestQueueHeadItem.md), which drops `lockExpiresAt`, while [`listAndLockHead()`](https://docs.apify.com/api/client/js/reference/class/RequestQueueClient.md#listAndLockHead) now yields the new [`LockedRequestQueueHeadItem`](https://docs.apify.com/api/client/js/reference/interface/LockedRequestQueueHeadItem.md), where the field is required.

[`addRequest()`](https://docs.apify.com/api/client/js/reference/class/RequestQueueClient.md#addRequest) and [`batchAddRequests()`](https://docs.apify.com/api/client/js/reference/class/RequestQueueClient.md#batchAddRequests) take [`RequestQueueClientRequestToAdd`](https://docs.apify.com/api/client/js/reference/interface/RequestQueueClientRequestToAdd.md), which is the stored request without the `id` the API assigns, so it follows the same optionality, and its `handledAt` is a `Date`.

### A scheduled Actor-task action takes its input as an object[](#a-scheduled-actor-task-action-takes-its-input-as-an-object)

`ScheduleActionRunActorTask.input` was typed as a `string`, and is now the object the specification describes. The same type backs [`create()`](https://docs.apify.com/api/client/js/reference/class/ScheduleCollectionClient.md#create) and [`update()`](https://docs.apify.com/api/client/js/reference/class/ScheduleClient.md#update), so an action that passed its input as a JSON string has to pass the parsed object instead.

## Model types take the names of the OpenAPI schemas[](#model-types-take-the-names-of-the-openapi-schemas)

Each model type now has the name of the [OpenAPI specification](https://docs.apify.com/api/v2) schema it's built on. The API reference, the [Python client](https://docs.apify.com/api/client/python) and this client use the same name for the same object. For example, the result of `client.run(id).get()` is a [`Run`](https://docs.apify.com/api/client/js/reference/interface/Run.md), not an `ActorRun`.

The renames change only the names, not the shapes. Two of the types below merge into a type that already existed: `ScheduledActorRunOptions` into [`TaskOptions`](https://docs.apify.com/api/client/js/reference/interface/TaskOptions.md) and `MonthlyUsageCycle` into [`UsageCycle`](https://docs.apify.com/api/client/js/reference/interface/UsageCycle.md), because each pair was built on the same schema.

Where a schema name would clash with a JavaScript global or a class in the Apify SDK or Crawlee, the specification adds a `Resource` suffix, so a dataset is a [`DatasetResource`](https://docs.apify.com/api/client/js/reference/interface/DatasetResource.md) and a stored request is a [`RequestResource`](https://docs.apify.com/api/client/js/reference/interface/RequestResource.md).

The specification describes an Actor version as one `Version` schema, while the client splits it by source type. The union is now `Version`, and its base type and variants drop the `Actor` prefix to match.

| v2                                               | v3                            |
| ------------------------------------------------ | ----------------------------- |
| `AccountAndUsageLimits`                          | `AccountLimits`               |
| `Actor`                                          | `ActorResource`               |
| `ActorCollectionListItem`                        | `ActorListItem`               |
| `ActorDefaultRunOptions`                         | `DefaultRunOptions`           |
| `ActorEnvironmentVariable`                       | `EnvVar`                      |
| `ActorExampleRunInput`                           | `ExampleRunInput`             |
| `ActorRun`                                       | `Run`                         |
| `ActorRunListItem`                               | `RunListItem`                 |
| `ActorRunMeta`                                   | `RunMeta`                     |
| `ActorRunOptions`                                | `RunOptions`                  |
| `ActorRunStats`                                  | `RunStats`                    |
| `ActorRunUsage`                                  | `RunUsage`                    |
| `ActorStoreList`                                 | `StoreActor`                  |
| `ActorTaggedBuild`                               | `TaggedBuildInfo`             |
| `ActorTaggedBuilds`                              | `TaggedBuilds`                |
| `ActorVersion`                                   | `Version`                     |
| `ActorVersionGitHubGist`                         | `VersionGitHubGist`           |
| `ActorVersionGitRepo`                            | `VersionGitRepo`              |
| `ActorVersionSourceFile`                         | `SourceCodeFile`              |
| `ActorVersionSourceFiles`                        | `VersionSourceFiles`          |
| `ActorVersionTarball`                            | `VersionTarball`              |
| `AllowedHttpMethods`                             | `HttpMethod`                  |
| `BaseActorVersion`                               | `BaseVersion`                 |
| `BuildCollectionClientListItem`                  | `BuildListItem`               |
| `Current`                                        | `CurrentUsage`                |
| `Dataset`                                        | `DatasetResource`             |
| `FieldStatistics`                                | `DatasetFieldStatistics`      |
| `FinalActorVersion`                              | `FinalVersion`                |
| `KeyValueClientListKeysResult`                   | `ListOfKeys`                  |
| `KeyValueListItem`                               | `KeyValueStoreKey`            |
| `KeyValueStore`                                  | `KeyValueStoreResource`       |
| `MonthlyUsageCycle`                              | `UsageCycle`                  |
| `PricePerEventActorPricingInfo`                  | `PayPerEventActorPricingInfo` |
| `PricingInfo`                                    | `CurrentPricingInfo`          |
| `RequestQueue`                                   | `RequestQueueResource`        |
| `RequestQueueClientAddRequestResult`             | `RequestRegistration`         |
| `RequestQueueClientBatchRequestsOperationResult` | `BatchAddResult`              |
| `RequestQueueClientListAndLockHeadResult`        | `LockedRequestQueueHead`      |
| `RequestQueueClientListHeadResult`               | `RequestQueueHead`            |
| `RequestQueueClientListItem`                     | `RequestQueueHeadItem`        |
| `RequestQueueClientListRequestsResult`           | `ListOfRequests`              |
| `RequestQueueClientProlongRequestLockResult`     | `RequestLockInfo`             |
| `RequestQueueClientRequestSchema`                | `RequestResource`             |
| `RequestQueueClientUnlockRequestsResult`         | `UnlockRequestsResult`        |
| `ScheduledActorRunInput`                         | `ScheduleActionRunInput`      |
| `ScheduledActorRunOptions`                       | `TaskOptions`                 |
| `TaskList`                                       | `TaskListItem`                |
| `User`                                           | `UserPrivateInfo`             |
| `UserProxy`                                      | `ProxyResource`               |
| `Webhook`                                        | `WebhookResource`             |

## Responses are validated against the OpenAPI specification[](#responses-are-validated-against-the-openapi-specification)

Every response the client turns into a typed value is now checked against a [zod](https://zod.dev) schema generated from the same specification the types come from, the way the Python client validates its responses with pydantic. A response that doesn't match, whether a missing required field, a different type, or a value outside the documented range, throws a new [`ResponseValidationError`](https://docs.apify.com/api/client/js/reference/class/ResponseValidationError.md) (exported from `apify-client`) instead of being handed on as if it were what the type claims.

The check is deliberately lenient about growth: fields the specification doesn't describe pass through untouched, and an enum value it doesn't list is accepted too, so a new field or status on the API side isn't an error. What it catches is the API and its specification disagreeing, which previously surfaced as an `undefined` somewhere down the line. If you hit one, the specification is wrong or the API changed, so please [report it](https://github.com/apify/apify-client-js/issues).

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



const client = new ApifyClient({ token: 'MY-APIFY-TOKEN' });



try {

    await client.actor('my-actor').get();

} catch (error) {

    if (error instanceof ResponseValidationError) {

        console.log(error.message);

        // Response from GET https://api.apify.com/v2/actors/my-actor does not match the API schema:

        // Invalid input: expected string, received null at `name`

        // The API returned something its OpenAPI specification does not describe. Please report this at https://github.com/apify/apify-client-js/issues.

        console.log(error.issues); // [{ code: 'invalid_type', expected: 'string', path: ['name'], ... }]

    }

}
```

Bodies the specification leaves to you aren't validated: dataset items, key-value store records and logs are returned as before.

Two return types change as a result of describing what the endpoints really return:

* [`ScheduleClient.getLog()`](https://docs.apify.com/api/client/js/reference/class/ScheduleClient.md#getLog) was typed as `string | undefined`, even though the endpoint returns the log as a list of entries. It's now typed as [`ScheduleLogEntry[]`](https://docs.apify.com/api/client/js/reference/interface/ScheduleLogEntry.md), each entry carrying `message`, `level` and `createdAt`.
* [`TaskPublicConfig`](https://docs.apify.com/api/client/js/reference/interface/TaskPublicConfig.md) now follows the specification: `publishedAt` is optional and read-only, and `categorization`, which the specification doesn't describe, is gone from the type.

### Date fields are converted by the schemas[](#date-fields-are-converted-by-the-schemas)

The `Date` conversion moved into the schemas. A field the specification declares as a `date-time` comes back as a `Date`, wherever it sits in the response, and nothing else is touched. v2 walked every response and converted any field whose name ends in `At`, three levels deep, and passed the field on as a string when it didn't parse as a date.

* Date strings inside the bodies the API stores for you stay strings. A `somethingAt` in a request's `userData` or in a task's `input` is returned as written, so parse it yourself where you need a `Date`.
* A `date-time` field that carries anything other than an ISO 8601 date-time with a `Z` or a time-zone offset throws a `ResponseValidationError`, where v2 handed the string on.
* The field name no longer matters. A `date-time` field is converted whatever it's called.
* Nothing is skipped for depth. `webhook.dispatches().list()` returns `calls[].startedAt` as a `Date` on every listed dispatch, where v2 left it a string for sitting one level too deep.

## URL fields are normalized[](#url-fields-are-normalized)

Fields the specification marks as a URL, such as [`Run.containerUrl`](https://docs.apify.com/api/client/js/reference/interface/Run.md) or [`DatasetResource.consoleUrl`](https://docs.apify.com/api/client/js/reference/interface/DatasetResource.md), are parsed with the [WHATWG `URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL) parser as part of response validation, and the client hands back the parsed URL's serialization. In v2 you got the raw string from the API. In v3 the string can differ, most visibly by an added trailing slash. Normalization also lowercases the host, drops a default port, punycodes an internationalized host, and percent-encodes unsafe characters. Both forms denote the same URL under [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986#section-6.2). They're just different strings.

```
// An empty path becomes '/'.

new URL('https://abc123.runs.apify.net').href; // 'https://abc123.runs.apify.net/'



// The host is lowercased.

new URL('https://EXAMPLE.com/Path').href; // 'https://example.com/Path'



// A default port is dropped.

new URL('https://example.com:443/path').href; // 'https://example.com/path'



// An internationalized host is punycoded.

new URL('https://www.žluty.cz').href; // 'https://www.xn--luty-kbb.cz/'



// Unsafe characters are percent-encoded.

new URL('https://example.com/a b').href; // 'https://example.com/a%20b'
```

Code that compares a stored URL with a URL field has to compare normalized values:

```
const run = await client.run('my-run-id').get();

const storedUrl = 'https://abc123.runs.apify.net';



// The raw string no longer matches.

storedUrl === run.containerUrl; // false



// Normalize the stored side too.

new URL(storedUrl).href === run.containerUrl; // true
```

The affected fields are `Run.containerUrl`, `Task.standbyUrl`, `WebhookResource.requestUrl` (on the full webhook, on a list item, and on the webhook summary a dispatch carries), `DatasetResource.consoleUrl`, `DatasetResource.itemsPublicUrl`, `KeyValueStoreResource.consoleUrl`, `KeyValueStoreResource.keysPublicUrl`, `KeyValueStoreResource.recordsPublicUrl`, `KeyValueStoreKey.recordPublicUrl`, `RequestQueueResource.consoleUrl`, `StoreActor.url`, `StoreActor.userPictureUrl`, `UserProfile.pictureUrl`, and `UserProfile.websiteUrl`. Whether a field is normalized depends on its model. The specification doesn't mark `ActorResource.standbyUrl`, `ActorResource.pictureUrl`, `StoreActor.pictureUrl`, or the `url` of a request queue request as URLs, so those come back exactly as the API sent them.

A trailing slash appears only on a field the API returns without a path, so on `containerUrl`, `standbyUrl`, `websiteUrl`, and a `WebhookResource.requestUrl` you registered without one. The rest already carry a path, and normalization leaves it alone. To append to a URL field, use `new URL('status', run.containerUrl)` only when the field ends with a slash: a relative reference replaces the base's last path segment, so on `consoleUrl` it would drop the resource ID.

A URL field whose value isn't a valid absolute URL now fails response validation and throws [`ResponseValidationError`](https://docs.apify.com/api/client/js/reference/class/ResponseValidationError.md), the same as any other field that doesn't match the specification.

## `batchAddRequests()` rejects an oversized request before sending anything[](#batchaddrequests-rejects-an-oversized-request-before-sending-anything)

[`batchAddRequests()`](https://docs.apify.com/api/client/js/reference/class/RequestQueueClient.md#batchAddRequests) now measures the whole input before it sends the first batch. A request too large for the payload limit still throws the same error, and the message still names the request's index. What changed is that nothing has been sent by the time it throws. In v2 each batch was measured as it came up, so every batch before the oversized request had already gone out.

```
// In v2 the four batches before the oversized request had already been sent.

// In v3 nothing is sent.

await client.requestQueue('my-queue').batchAddRequests([...hundredRequests, oversizedRequest]);
```

Code that treated the throw as "some of these landed" and reconciled the queue afterwards can drop the reconciliation.

## A string body with a JSON content type is sent as it is[](#a-string-body-with-a-json-content-type-is-sent-as-it-is)

A string body sent with an explicit `application/json` content type now goes out verbatim. Axios used to parse it to check that it was valid JSON, and wrapped it in a JSON string literal when it wasn't. The client skips that step so that `batchAddRequests()` can send a body it has already serialized.

[`setRecord()`](https://docs.apify.com/api/client/js/reference/class/KeyValueStoreClient.md#setRecord) is where you'd notice. Storing a non-JSON string under `contentType: 'application/json'` used to save `"my value"`, quotes included, and now saves `my value`, which [`getRecord()`](https://docs.apify.com/api/client/js/reference/class/KeyValueStoreClient.md#getRecord) can't parse back:

```
// v2 stored `"my value"`, v3 stores `my value`.

await client.keyValueStore('my-store').setRecord({

    key: 'my-key',

    value: 'my value',

    contentType: 'application/json',

});
```

Give a record a content type matching what it holds, such as `text/plain`, or pass the value as an object and let the client serialize it.

The same applies to a string input passed with a JSON `contentType` to [`start()`](https://docs.apify.com/api/client/js/reference/class/ActorClient.md#start), [`call()`](https://docs.apify.com/api/client/js/reference/class/ActorClient.md#call), or [`metamorph()`](https://docs.apify.com/api/client/js/reference/class/RunClient.md#metamorph). When the string wasn't valid JSON, v2 handed the API the string wrapped in quotes. v3 hands it over as it is.

## Timeouts are configured per tier[](#timeouts-are-configured-per-tier)

The `timeoutSecs` option of the [`ApifyClient`](https://docs.apify.com/api/client/js/reference/class/ApifyClient.md) constructor is gone. Every method takes its timeout from one of three tiers, and the constructor sets the duration of each tier, along with a cap on any single request attempt:

```
- const client = new ApifyClient({ token: 'MY-APIFY-TOKEN', timeoutSecs: 360 });   // v2

+ const client = new ApifyClient({                                                 // v3

+     token: 'MY-APIFY-TOKEN',

+     timeoutShortSecs: 5,

+     timeoutMediumSecs: 30,

+     timeoutLongSecs: 360,

+     timeoutMaxSecs: 360,

+ });
```

For what each tier covers and which one a method is assigned, see [Timeouts](https://docs.apify.com/api/client/js/docs/concepts/timeouts.md).

In v2 only the dataset, key-value store and request queue clients picked a timeout per method, and everything else ran with the global 360 seconds. A metadata call such as `actor.get()` now gets the 5 seconds of the `short` tier and most `list()` calls the 30 of `medium`, so a call that used to wait out a slow API can fail sooner. A few methods move the other way, to the 360 seconds of `long`: [`RequestQueueClient.unlockRequests()`](https://docs.apify.com/api/client/js/reference/class/RequestQueueClient.md#unlockRequests) from 30 seconds, and [`DatasetClient.createItemsPublicUrl()`](https://docs.apify.com/api/client/js/reference/class/DatasetClient.md#createItemsPublicUrl), [`KeyValueStoreClient.getRecordPublicUrl()`](https://docs.apify.com/api/client/js/reference/class/KeyValueStoreClient.md#getRecordPublicUrl) and [`KeyValueStoreClient.createKeysPublicUrl()`](https://docs.apify.com/api/client/js/reference/class/KeyValueStoreClient.md#createKeysPublicUrl) from 5. Where you need a different duration, pass the `timeoutSecs` option, which replaces the tier of the method for that call:

```
await client.actor('my-actor').get({ timeoutSecs: 'long' });
```

`timeoutSecs` means the request timeout on every method, so the run timeout of [`ActorClient.start()`](https://docs.apify.com/api/client/js/reference/class/ActorClient.md#start) and [`call()`](https://docs.apify.com/api/client/js/reference/class/ActorClient.md#call), [`TaskClient.start()`](https://docs.apify.com/api/client/js/reference/class/TaskClient.md#start) and [`call()`](https://docs.apify.com/api/client/js/reference/class/TaskClient.md#call), and [`RunClient.resurrect()`](https://docs.apify.com/api/client/js/reference/class/RunClient.md#resurrect) is renamed:

```
- await client.actor('my-actor').call(input, { timeout: 300 });        // v2

+ await client.actor('my-actor').call(input, { runTimeoutSecs: 300 }); // v3
```

TypeScript reports a leftover `timeout` at compile time, also when the options come from a variable rather than an object literal. At runtime the call throws an `ArgumentValidationError` that names `runTimeoutSecs`, instead of silently dropping the run limit. `{ timeout: 0 }`, which asked for an unlimited run in v2, becomes `{ runTimeoutSecs: 0 }`.

The `timeoutSecs` option of [`KeyValueStoreClient.setRecord()`](https://docs.apify.com/api/client/js/reference/class/KeyValueStoreClient.md#setRecord) keeps its name and its meaning for a number of seconds, and now takes a tier name or `'noTimeout'` as well. `client.requestQueue(id, { timeoutSecs })` still takes a number of seconds that caps the tier of every request the queue client sends.

Neither accepts `0` any more. In v2, `setRecord(record, { timeoutSecs: 0 })` meant no timeout and `client.requestQueue(id, { timeoutSecs: 0 })` meant no cap. v3 rejects both with an `ArgumentValidationError`, so pass `'noTimeout'` to `setRecord()` and leave the option out of `requestQueue()`.

`client.httpClient.call()` takes `timeoutSecs` where it read the axios `timeout` in milliseconds. A direct call that passed `timeout: 30000` has to become `timeoutSecs: 30`. In JavaScript, a leftover `timeout` is ignored rather than rejected. A direct call without `timeoutSecs` gets the 30 seconds of `medium`, where v2 used the global 360.

## Request compression is configurable[](#request-compression-is-configurable)

The [`ApifyClient`](https://docs.apify.com/api/client/js/reference/class/ApifyClient.md) constructor takes a `compression` option: `'brotli'`, `'gzip'`, `'zstd'`, or an [`HttpCompressor`](https://docs.apify.com/api/client/js/reference/interface/HttpCompressor.md) for a custom quality or algorithm. The default stays brotli at quality 6. For the rules that decide which bodies get compressed, see [HTTP compression](https://docs.apify.com/api/client/js/docs/concepts/http-compression.md).

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



const client = new ApifyClient({ token: 'MY-APIFY-TOKEN', compression: 'gzip' });

const bestClient = new ApifyClient({

    token: 'MY-APIFY-TOKEN',

    compression: new BrotliHttpCompressor({ quality: 11 }),

});
```

The silent fallback is gone. In v2, a body was sent gzipped when brotli failed, and uncompressed when gzip failed too, which could happen on a runtime whose `node:zlib` is a polyfill or a Node.js compatibility shim. In v3 the configured compressor is the only one the client runs, and its error fails the request. On such a runtime, pass `compression: 'gzip'` or a custom compressor.

Which bodies get compressed changed as well:

* A body whose `Content-Type` is already compressed, such as an image, audio, video or an archive, is sent as it is. v2 compressed any string or `Buffer` of 1 kB or more. See [Already-compressed payloads](https://docs.apify.com/api/client/js/docs/concepts/http-compression.md#already-compressed-payloads).
* A `Uint8Array`, another typed array, or an `ArrayBuffer` is compressed once it reaches the same 1 kB threshold, where v2 compressed only strings and `Buffer`s, so a request carrying one gains a `content-encoding` header.

The API accepts every encoding the client sends, `br`, `gzip`, and `zstd`, so neither change needs anything on your side.

## `versions().list()` and `envVars().list()` lose their pagination options[](#versionslist-and-envvarslist-lose-their-pagination-options)

[`ActorVersionCollectionClient.list()`](https://docs.apify.com/api/client/js/reference/class/ActorVersionCollectionClient.md#list) and [`ActorEnvVarCollectionClient.list()`](https://docs.apify.com/api/client/js/reference/class/ActorEnvVarCollectionClient.md#list) accept only the `timeoutSecs` and `signal` options. Neither endpoint reads `offset`, `limit` or `desc`, and both return every item in one response, so `chunkSize` had nothing to size either. The `ActorVersionCollectionListOptions` and `ActorEnvVarCollectionListOptions` types that declared those four options, deprecated since v2.21.0, are gone from the package. A call that passed any of them no longer compiles, and throws an `ArgumentValidationError` about an unrecognized key in JavaScript. Drop them and the call returns the same items as before.

## `limit` counts scanned rows when iterating `listItems()`[](#limit-counts-scanned-rows-when-iterating-listitems)

Iterating [`DatasetClient.listItems()`](https://docs.apify.com/api/client/js/reference/class/DatasetClient.md#listItems) with `for await` pages through the dataset by `offset` and `limit`. The API applies both to the dataset's rows before `clean`, `skipEmpty`, `skipHidden` and `unwind` reshape them, so a page can return fewer items than the rows it covered, or more. v2 advanced the offset and counted down `limit` by the items each page returned. A filter made the next page re-read rows the previous one had covered, `unwind` made it skip rows, and a page that came back empty ended the loop even when rows remained behind it.

v3 advances and stops by the number of rows the API scanned, taken from the `x-apify-pagination-count` header. `limit` therefore caps the rows scanned, the same way it does on a single awaited `listItems()` call and in the API itself. With a filter set, the loop can yield fewer than `limit` items, each of them once. In v2 the same call made up the difference with items it had already yielded, or stopped early. With `unwind`, the loop can yield more than `limit` items. To collect a fixed number of items from a filtered dataset, count them in the loop:

```
const items = [];

for await (const item of client.dataset('dataset-id').listItems({ clean: true, chunkSize: 100 })) {

    items.push(item);

    if (items.length === 100) break;

}
```

`PaginatedList.count` on a page from `listItems()` follows the same header. It is the number of rows the API scanned for the page, or the number of items returned when that is larger. In v2 it was always `items.length`. To page through a filtered dataset by hand, advance `offset` by `count`. With `unwind`, cap the step at `limit`, since an unwound page can return more items than the rows it scanned.

The cursor-based iterators, `listKeys()`, `listRequests()` and `paginateRequests()`, are unchanged.

## Offset iterators page until they find no rows[](#offset-iterators-page-until-they-find-no-rows)

Iterating a `list()` method or `listItems()` with `for await` no longer stops at the `total` reported by the first page. v2 never requested rows past it, so a dataset that a running Actor kept pushing to was cut off at the size it had when the loop started. v3 keeps requesting pages until one scans no rows, or until your `limit` is reached. The loop yields the rows added while it runs, and it sends one more request at the end to find the empty page.

Each page advances `offset` by the page's `count` or by the number of items it returned, whichever is larger, capped at the page's `limit`. On a `list()` page, `count` is usually the number of items returned. When the API drops entries after counting them, as `store().list()` can, the next page starts after the dropped entries and does not read the same ones again. A page whose `count` is above zero continues the loop even when it returned no items.

## `store().list()` no longer searches or sorts[](#storelist-no-longer-searches-or-sorts)

[`StoreCollectionClient.list()`](https://docs.apify.com/api/client/js/reference/class/StoreCollectionClient.md#list) loses its `search` and `sortBy` options. A call that passes either no longer compiles, and throws an `ArgumentValidationError` about an unrecognized key in JavaScript.

### Search moved to `store().search()`[](#search-moved-to-storesearch)

Search with the new [`StoreCollectionClient.search()`](https://docs.apify.com/api/client/js/reference/class/StoreCollectionClient.md#search) instead:

```
// v2

const { items } = await client.store().list({ search: 'web scraper', limit: 10 });



// v3

const { items } = await client.store().search({ search: 'web scraper', limit: 10 });
```

The API answers a search differently from a listing. It returns the Actors that match the query best as one page of at most 100, ordered by relevance. It ignores `offset`, and it reports the number of Actors returned as `total`, not the number of Actors that match. A search therefore can't be paged through, and iterating one would request the same page again and again.

`search()` follows that. The query stays in the options object, where `search` is now a required, non-empty string. It accepts `limit` and the `category`, `username`, `pricingModel` and `includeUnrunnableActors` filters, and rejects `offset`, `chunkSize` and `sortBy`. It resolves to an object with `items` and `limit` only, and it is not async-iterable. The API reduces a `limit` above 100 to 100, and the returned `limit` is the one it applied. When `items.length` equals it, more Actors may match than were returned, so narrow the search with a more specific query or with the filters.

`list()` still pages through the whole Store, alone or with the same filters.

### `sortBy` is gone[](#sortby-is-gone)

The API ignores `sortBy`, whatever its value and whatever it is combined with. A listing comes in Store order and a search comes by relevance. The option is therefore gone from `StoreCollectionListOptions`, and `search()` never had it. Drop it from your calls, and sort the results on your side if you need a different order:

```
// v2

const { items } = await client.store().list({ username: 'apify', sortBy: 'newest' });



// v3

const { items } = await client.store().list({ username: 'apify' });
```

## The last deprecated options are gone[](#the-last-deprecated-options-are-gone)

Three deprecated options have been removed.

`restartOnError`, deprecated since v2.19.0, is gone from [`ActorCollectionCreateOptions`](https://docs.apify.com/api/client/js/reference/interface/ActorCollectionCreateOptions.md) and `ActorUpdateOptions`, so [`ActorCollectionClient.create()`](https://docs.apify.com/api/client/js/reference/class/ActorCollectionClient.md#create) and [`ActorClient.update()`](https://docs.apify.com/api/client/js/reference/class/ActorClient.md#update) no longer accept it at the top level. Pass it inside `defaultRunOptions` instead, as the deprecation notice advised. Only the types changed: the client doesn't validate the fields `create()` and `update()` send, so in JavaScript a top-level `restartOnError` still reaches the API.

`exclusiveStartId`, deprecated since v2.23.2, is gone from [`listRequests()`](https://docs.apify.com/api/client/js/reference/class/RequestQueueClient.md#listRequests) and [`paginateRequests()`](https://docs.apify.com/api/client/js/reference/class/RequestQueueClient.md#paginateRequests). Both paginate by `cursor` alone now, and passing `exclusiveStartId` throws an `ArgumentValidationError` about an unrecognized key. In v2 the two were mutually exclusive, so the error about combining them is gone as well. Responses are unaffected, since the API still echoes `exclusiveStartId` back in the request listing.

`disableRedirect`, deprecated since v1.1.0, is gone from [`getRecord()`](https://docs.apify.com/api/client/js/reference/class/KeyValueStoreClient.md#getRecord). It had no effect since then and only logged a deprecation warning. Passing it now throws an `ArgumentValidationError` about an unrecognized key, so drop it.

## `getStreamedLog()` takes `since` instead of `fromStart`[](#getstreamedlog-takes-since-instead-of-fromstart)

[`RunClient.getStreamedLog()`](https://docs.apify.com/api/client/js/reference/class/RunClient.md#getStreamedLog) and [`StreamedLog`](https://docs.apify.com/api/client/js/reference/class/StreamedLog.md) no longer take the `fromStart` option. Pass a `Date` as `since` instead, and only the lines logged at that time or later are redirected. Without it, the whole log is redirected, as with `fromStart: true` before.

```
- const streamedLog = await client.run('run-id').getStreamedLog({ fromStart: false }); // v2

+ const streamedLog = await client.run('run-id').getStreamedLog({ since: new Date() }); // v3
```

`getStreamedLog()` now validates its options, so passing `fromStart` or any other unknown option throws an `ArgumentValidationError`.

A log stream that is interrupted while the run is still going is now reopened, and the redirection continues after the last redirected line. In v2 the redirection stopped with a warning. For details, see [Redirecting Actor run logs](https://docs.apify.com/api/client/js/docs/concepts/logging.md#redirecting-actor-run-logs).

## Actor run input is no longer `unknown`[](#actor-run-input-is-no-longer-unknown)

[`ActorClient.start()`](https://docs.apify.com/api/client/js/reference/class/ActorClient.md#start), [`call()`](https://docs.apify.com/api/client/js/reference/class/ActorClient.md#call), [`validateInput()`](https://docs.apify.com/api/client/js/reference/class/ActorClient.md#validateInput) and [`RunClient.metamorph()`](https://docs.apify.com/api/client/js/reference/class/RunClient.md#metamorph) took their `input` as `unknown`, so any value compiled, including ones the client cannot send.

The input is now typed `ActorInput`, which accepts a plain object, an array of plain objects, or raw bytes as a `Uint8Array` (such as a `Buffer`) or an `ArrayBuffer`. The client serializes objects and arrays into the request body and sends bytes as they are. Any other value stops compiling, including a `Date`, `Map`, `Set` or function, and a value typed `unknown`, which has to be narrowed or cast first. To run an Actor without input, omit the argument or pass `undefined`.

```
- await client.actor('my-actor').call(null, { memory: 1024 }); // v2

+ await client.actor('my-actor').call(undefined, { memory: 1024 }); // v3
```

An input declared as an `interface` or a class stops compiling as well, since `ActorInput` needs an index signature and neither gets one implicitly. Declare the input type as a `type` alias, or spread the value into a new object:

```
- interface MyInput { url: string } // v2

+ type MyInput = { url: string }; // v3



- await client.actor('my-actor').call(input); // v2, with an interface-typed `input`

+ await client.actor('my-actor').call({ ...input }); // v3
```

A raw `string` body stops compiling too, with or without a `contentType`. Pass the input as an object and let the client serialize it:

```
- await client.actor('my-actor').start('some=body', { contentType: 'application/x-www-form-urlencoded' }); // v2

+ await client.actor('my-actor').start({ some: 'body' }); // v3
```

Dropping the `contentType` sends the body as JSON, so the run's `INPUT` record changes content type with it. To keep the form encoding, pass the object and the option together: the client form-encodes an object whenever `contentType` is `application/x-www-form-urlencoded`.

`metamorph()`'s `input` is optional now, so `metamorph('target-actor')` compiles where it previously needed an explicit `undefined`.

Nothing changes at runtime. `TaskClient.start()` and `call()` keep taking a `Dictionary`: a task's input overrides are merged into the input saved on the task, so they are always an object.

## `TaskClient.call()` redirects the run log[](#taskclientcall-redirects-the-run-log)

In Node.js, [`TaskClient.call()`](https://docs.apify.com/api/client/js/reference/class/TaskClient.md#call) now redirects the log of the run it starts to your process while it waits, the way [`ActorClient.call()`](https://docs.apify.com/api/client/js/reference/class/ActorClient.md#call) has done since v2.20.0. It takes the same `log` option. Pass `null` to keep the run log out of your output:

```
- await client.task('my-task').call(); // v2

+ await client.task('my-task').call(undefined, { log: null }); // v3
```

For both methods, a failure to set the redirection up no longer rejects `call()`. The run has already started by then, so `call()` logs a warning and waits for the run without redirecting its log. In v2, `ActorClient.call()` rejected with the error of the failed request.

## Proxies are opt-in[](#proxies-are-opt-in)

In v2 the client read the `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` environment variables on its own, through the `proxy-agent` package. v3 sends its requests through the `fetch` of the runtime and no longer depends on `proxy-agent`, so in Node.js a proxy applies only when Node.js itself is told to read those variables. Start it with `NODE_USE_ENV_PROXY=1`, which Node.js 22.21 and 24 and newer support (the `--use-env-proxy` flag does the same on 22.21 and on 24.5 and newer):

```
export NODE_USE_ENV_PROXY=1

export HTTP_PROXY=http://proxy.example.com:3128

export HTTPS_PROXY=http://proxy.example.com:3128
```

An application that can't control how Node.js is started, such as a command-line tool, can call [`http.setGlobalProxyFromEnv()`](https://nodejs.org/api/http.html#httpsetglobalproxyfromenvproxyenv) before its first request instead, on Node.js 24.14 and newer.

Without the switch, requests go out directly, which fails in an environment that only lets traffic out through the proxy. When that happens while a proxy variable is set, the client logs a warning that names the variable and the switch. On Node.js 22.15 to 22.20, where `fetch` can't be routed through a proxy this way, upgrade Node.js or pass the client a `fetch` or an agent that goes through the proxy. See [Proxies](https://docs.apify.com/api/client/js/docs/concepts/custom-http-clients.md#proxies) for all the options.

Two details of the v2 behavior are gone for good. Node.js doesn't read `ALL_PROXY`, which v2 used as a fallback. The `proxy` and `https-proxy` settings in `.npmrc`, which npm exports as `npm_config_proxy` and `npm_config_https_proxy` under `npm run` and v2 read as well, no longer reach the client either.

Dropping `proxy-agent` also removes the `[DEP0169] DeprecationWarning` about `url.parse()` that Node.js 24 and newer printed on the client's first request when the client was bundled into the application.

## Non-public members no longer carry an underscore[](#non-public-members-no-longer-carry-an-underscore)

Members declared `private` or `protected` had a leading underscore on top of the keyword in v2, and the underscore is gone in v3. Code that calls only the public methods of a client is unaffected. A class that extends one of the client classes and calls a protected helper has to switch to the new name. `ApiClient`, `ResourceClient` and `ResourceCollectionClient` are not exported, so you reach their members by extending a concrete client such as `ActorClient`.

| Class                      | v2                               | v3                             |
| -------------------------- | -------------------------------- | ------------------------------ |
| `ApiClient`                | `_url()`                         | `buildUrl()`                   |
| `ApiClient`                | `_publicUrl()`                   | `buildPublicUrl()`             |
| `ApiClient`                | `_params()`                      | `buildParams()`                |
| `ApiClient`                | `_subResourceOptions()`          | `subResourceOptions()`         |
| `ApiClient`                | `_toSafeId()`                    | `toSafeId()`                   |
| `ApiClient`                | `_listPaginatedFromCallback()`   | `listPaginatedFromCallback()`  |
| `ResourceClient`           | `_get()`                         | `getResource()`                |
| `ResourceClient`           | `_update()`                      | `updateResource()`             |
| `ResourceClient`           | `_delete()`                      | `deleteResource()`             |
| `ResourceClient`           | `_waitForFinish()`               | `waitForJobFinish()`           |
| `ResourceCollectionClient` | `_list()`                        | `listResources()`              |
| `ResourceCollectionClient` | `_listPaginated()`               | `listResourcesPaginated()`     |
| `ResourceCollectionClient` | `_create()`                      | `createResource()`             |
| `ResourceCollectionClient` | `_getOrCreate()`                 | `getOrCreateResource()`        |
| `RequestQueueClient`       | `_batchAddRequests()`            | `addRequestBatch()`            |
| `RequestQueueClient`       | `_batchAddRequestsWithRetries()` | `addRequestBatchWithRetries()` |

A helper got a suffix wherever the bare name would collide with a public method of the same class, which is why `_get()` is now `getResource()` and not `get()`.

The signatures changed along with the names:

* `getResource()`, `updateResource()`, `listResources()`, `listResourcesPaginated()`, `createResource()`, `getOrCreateResource()` and `waitForJobFinish()` take the zod schema that validates the response as their first argument.
* The timeout is a required number of seconds or a tier name, where v2 took an optional number of milliseconds. `_delete(5000)` renamed to `deleteResource(5000)` waits 5000 seconds.
* `addRequestBatch()` and `addRequestBatchWithRetries()` take requests already serialized to JSON, where v2 took request objects.

[`LoggerActorRedirect`](https://docs.apify.com/api/client/js/reference/class/LoggerActorRedirect.md) keeps `_log()`, since it overrides the method of that name on the `Logger` base class in `@apify/log`.

The `clientMethod` field on [`ApifyApiError`](https://docs.apify.com/api/client/js/reference/class/ApifyApiError.md) is parsed from the stack trace, and a public method that delegates to one of these helpers is reported under the helper's name. An error from `client.actor(id).get()` says `ActorClient.getResource`, where v2 said `ActorClient.get`. Adjust anything that matches on these values in your logs.

### Private members are private at runtime[](#private-members-are-private-at-runtime)

Members that v2 declared `private` are declared with a `#` in v3, so the JavaScript runtime enforces the boundary, where v2 relied on the type checker. Code that reached one of them through a cast, such as `(client.httpClient as any)._isRetryableError(error)`, finds nothing under the old name: reading it gives `undefined`, and calling it throws a `TypeError`. They also don't appear when you spread an instance, iterate `Object.keys()` on it, or pass it to `JSON.stringify()`. The `protected` helpers in the table keep the `protected` keyword, so a subclass can call them.

## Node.js-only features follow the bundler's target[](#nodejs-only-features-follow-the-bundlers-target)

Some features need Node.js APIs: log redirection with [`RunClient.getStreamedLog()`](https://docs.apify.com/api/client/js/reference/class/RunClient.md#getStreamedLog), request body compression, and the `User-Agent` header.

In v2 the client detected the runtime when one of them was used, so a Node.js application bundled for a browser or a neutral target kept them all. In v3 the implementation is picked when the import is resolved, so the bundler's conditions decide. Without the `node` condition, `getStreamedLog()` returns `undefined`, and requests go out uncompressed and without the client's `User-Agent` header.

Enable the `node` condition when you bundle for Node.js. esbuild sets it through `platform: 'node'`, webpack through `resolve.conditionNames`, and Vite through `resolve.conditions` for a client build. A Vite SSR build includes `node` already.

A test runner that resolves the `browser` condition decides the same way. Jest's `jsdom` environment resolves it, so a Node.js test suite running under it loses them unless you list the `node` condition:

```
// jest.config.mjs

export default {

    testEnvironment: 'jsdom',

    testEnvironmentOptions: { customExportConditions: ['node'] },

};
```

Running on Node.js without a bundler is unaffected, and the pre-built browser bundle leaves log redirection, compression and the `User-Agent` header out, as in v2. For what bundling for a non-Node.js target takes, see [Bundled environments](https://docs.apify.com/api/client/js/docs/concepts/bundled-environments.md).

## Streams and raw bytes are web types[](#streams-and-raw-bytes-are-web-types)

The client returns the same types in every runtime, where v2 returned Node.js types in Node.js and something else in a browser.

### A streamed response is a web `ReadableStream`[](#a-streamed-response-is-a-web-readablestream)

[`LogClient.stream()`](https://docs.apify.com/api/client/js/reference/class/LogClient.md#stream) and [`getRecord({ stream: true })`](https://docs.apify.com/api/client/js/reference/class/KeyValueStoreClient.md#getRecord) resolve to a web [`ReadableStream`](https://developer.mozilla.org/docs/Web/API/ReadableStream) of `Uint8Array` chunks, and so do the new `stream` option of [`DatasetClient.downloadItems()`](https://docs.apify.com/api/client/js/reference/class/DatasetClient.md#downloadItems) and `responseType: 'stream'`. In v2 they resolved to a Node.js `Readable`, and `getRecord({ stream: true })` threw outside Node.js.

In Node.js, a `for await` loop over the stream keeps working. Code that calls `pipe()`, `on('data')`, `destroy()` or passes the stream to an API that takes a `Readable` has to convert it first, or switch to `pipeTo()` and `cancel()`:

```
import { Readable } from 'node:stream';

import type { ReadableStream } from 'node:stream/web';



const record = await client.keyValueStore('my-store').getRecord('video.mp4', { stream: true });

Readable.fromWeb(record.value as ReadableStream).pipe(fs.createWriteStream('video.mp4'));
```

The cast is only needed in a TypeScript project that includes the `DOM` library, whose `ReadableStream` type the Node.js types don't accept.

[`setRecord()`](https://docs.apify.com/api/client/js/reference/class/KeyValueStoreClient.md#setRecord) takes a web `ReadableStream` as well as a `Readable`, so code that copies a record by passing the streamed `value` on keeps working. v2 serialized a web `ReadableStream` to JSON and stored `{}`.

### Raw bytes are typed as `Uint8Array`[](#raw-bytes-are-typed-as-uint8array)

A binary key-value store record, the result of the `buffer` option of `getRecord()`, and of `DatasetClient.downloadItems()` are typed `Uint8Array`, where v2 typed them `Buffer`.

In Node.js the value is still a `Buffer`, which is a `Uint8Array`, so only the types change there: code that calls a `Buffer` method such as `toString('utf8')` no longer compiles. Decode the bytes with `TextDecoder`, or view them as a `Buffer`:

```
const { value } = await client.keyValueStore('my-store').getRecord('page.html', { buffer: true });

const html = new TextDecoder().decode(value);

const buffer = Buffer.from(value.buffer, value.byteOffset, value.byteLength);
```

In a browser the value is now a `Uint8Array`, where v2 returned an `ArrayBuffer`. Code that needs the `ArrayBuffer`, for a `DataView` for example, gets it from `value.buffer`, `value.byteOffset` and `value.byteLength`.

### Response bodies are decoded by `TextDecoder`[](#response-bodies-are-decoded-by-textdecoder)

v2 decoded response bodies with `Buffer` in Node.js, and decoded only UTF-8 ones in browsers. v3 decodes them with `TextDecoder` everywhere. The two support different charsets, so a `content-type` header carrying one can be handled differently:

* `iso-8859-1` and other charsets only `TextDecoder` knows decode to a string, where v2 handed back raw bytes.
* `hex`, `base64`, `base64url`, `binary`, `ucs2` and `utf16le`, which only `Buffer` knows, come back as raw bytes. v2 passed them to `buffer.toString()`, which decoded `binary`, `ucs2` and `utf16le` bodies, and turned the bytes into hex or base64 text for the others.
* `ascii` and `latin1` are read as aliases for `windows-1252`. A byte above `0x7F` in an `ascii` body decodes to the character that encoding gives it, where v2 masked the byte down to seven bits. A byte between `0x80` and `0x9F` in a `latin1` body decodes to a printable character such as `€`, where v2 gave a control character.

Code that depended on one of these has to convert the value itself. A body with no charset or with a UTF-8 one is unaffected, and that covers everything the Apify API sends.

## The HTTP client is pluggable, and `fetch` replaces axios[](#the-http-client-is-pluggable-and-fetch-replaces-axios)

`ApifyClient` sends its requests through an HTTP client you can replace. [`HttpClient`](https://docs.apify.com/api/client/js/reference/class/HttpClient.md) is now the abstract base holding the shared request pipeline. The client the `ApifyClient` uses by default is [`FetchHttpClient`](https://docs.apify.com/api/client/js/reference/class/FetchHttpClient.md), built on the `fetch` of the runtime, so `axios` and `proxy-agent` are no longer dependencies of the package. A custom client extends `HttpClient`, implements `sendRequest()` and is plugged in with [`ApifyClient.withCustomHttpClient()`](https://docs.apify.com/api/client/js/reference/class/ApifyClient.md#withCustomHttpClient). See [HTTP clients](https://docs.apify.com/api/client/js/docs/concepts/custom-http-clients.md) for the contract. Decoupling the pipeline from axios changes a few details of the public surface.

### The axios transport is opt-in[](#the-axios-transport-is-opt-in)

The transport of v2 is still available as `AxiosHttpClient`, from an entry point of its own. Use it when your code depends on axios behavior, or to rule the new transport out while you debug a difference after the upgrade. Install `axios`, which is an optional peer dependency of the client, and plug the client in:

```
npm install axios
```

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

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



const client = ApifyClient.withCustomHttpClient({

    token: 'MY-APIFY-TOKEN',

    httpClient: new AxiosHttpClient({ maxRetries: 4 }),

});
```

It no longer reads the proxy environment variables either. Pass a proxy agent in its `httpAgent` and `httpsAgent` options instead, as described in [Proxies](https://docs.apify.com/api/client/js/docs/concepts/custom-http-clients.md#proxies). It also keeps a separate keep-alive agent for each of HTTP and HTTPS, where v2 shared one.

The entry point is meant for Node.js. An `ApifyClient` imported from the pre-built browser bundle rejects an `AxiosHttpClient`, so a browser application that passed `requestInterceptors` in v2 has to move to a `fetch` wrapper.

### Idle connections close sooner in Node.js[](#idle-connections-close-sooner-in-nodejs)

`fetch` in Node.js closes a connection that has been idle for about 4 seconds, where the agents of v2 kept it until the server closed it. A request that follows a longer pause therefore opens a new connection. To keep them open longer, see [Default HTTP client](https://docs.apify.com/api/client/js/docs/concepts/custom-http-clients.md#default-http-client).

### Transport errors are the errors of `fetch`[](#transport-errors-are-the-errors-of-fetch)

An error that isn't an API error, such as a refused connection or a timeout, is no longer an `AxiosError`. A network failure is the `TypeError` that `fetch` throws, with the underlying error and its `code` in `cause` in Node.js, where v2 had the `code` on the error itself. A timeout is a `DOMException` named `TimeoutError` with the same `timeout of 30000ms exceeded` message as in v2. Use [`client.httpClient.isTimeoutError(error)`](https://docs.apify.com/api/client/js/reference/class/HttpClient.md#isTimeoutError) to recognize one whatever the transport, instead of checking for `AxiosError` or `ECONNABORTED`.

The timeout of a request runs until the response headers arrive and starts over with every chunk of the response body. In Node.js, a stream or `Blob` request body restarts it with every chunk that is read from it too. Any other upload, such as a `Buffer`, has to finish within the timeout, where v2 counted any socket activity as progress. Node.js also ends a `fetch` that waits more than 300 seconds for the response headers or for the next chunk of the body, whatever the timeout of the request. That covers streamed responses too, so the idle limit of a stream from [`LogClient.stream()`](https://docs.apify.com/api/client/js/reference/class/LogClient.md#stream), and of the log redirection built on it, drops to 300 seconds. In v2 such a stream failed once it received nothing for as long as the client's `timeoutSecs`, 360 seconds by default.

Response headers are the ones the server sent. `fetch` decodes a compressed body and leaves `content-encoding` and `content-length` in `ApifyResponse.headers` as they were, where axios removed `content-encoding`.

### `requestInterceptors` moved to `AxiosHttpClient`[](#requestinterceptors-moved-to-axioshttpclient)

Axios request interceptors are a feature of the axios transport, so the option left `ApifyClientOptions`. An interceptor that only adds a fixed header to every request, such as `x-apify-integration-platform`, can be replaced by the new `headers` option of `ApifyClientOptions`, without touching axios:

```
  const client = new ApifyClient({

      token: 'MY-APIFY-TOKEN',

-     requestInterceptors: [

-         (config) => {

-             config.headers['x-apify-integration-platform'] = 'my-platform';

-             return config;

-         },

-     ],

+     headers: { 'x-apify-integration-platform': 'my-platform' },

  });
```

An interceptor that computes something per request, such as a token read at call time, becomes a wrapper around `fetch` passed to a [`FetchHttpClient`](https://docs.apify.com/api/client/js/reference/class/FetchHttpClient.md), as shown in [HTTP clients](https://docs.apify.com/api/client/js/docs/concepts/custom-http-clients.md#default-http-client). To keep the interceptor as it is, move it to an `AxiosHttpClient` that you plug in. The retry and timeout options move along with it:

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

+ import { AxiosHttpClient } from 'apify-client/axios';



- const client = new ApifyClient({

-     token: 'MY-APIFY-TOKEN',

-     maxRetries: 4,

-     requestInterceptors: [addRequestId],

- });

+ const client = ApifyClient.withCustomHttpClient({

+     token: 'MY-APIFY-TOKEN',

+     httpClient: new AxiosHttpClient({ maxRetries: 4, requestInterceptors: [addRequestId] }),

+ });
```

An interceptor now sees the request as the shared pipeline prepared it: the headers merged, the query string already encoded into `url` so `params` is not set, and the body already serialized to a string or `Buffer` and compressed. Under v2 the interceptors ran before serialization and saw the original object.

### `ApifyRequestConfig` and `ApifyResponse` no longer extend the axios types[](#apifyrequestconfig-and-apifyresponse-no-longer-extend-the-axios-types)

The request `httpClient.call()` takes and the response it resolves to, which `RunClient.charge()` also returns, are now transport-neutral. `ApifyResponse` carries `status`, `headers`, `data` and `config`, without the `statusText`, `request` and axios-specific `config` fields. `ApifyRequestConfig` accepts `url`, `method`, `params`, `headers`, `data`, `timeoutSecs`, `responseType`, `stringifyFunctions`, `doNotRetryTimeouts` and `signal`, so an axios-only option such as `maxRedirects` is rejected by the types. The `forceBuffer` flag became `responseType: 'buffer'`, and `responseType` takes `'parsed'`, `'buffer'` or `'stream'` instead of the axios values. `url` and `method` are required, and `method` takes uppercase names only, so `method: 'get'` no longer compiles. `ApifyResponse.headers` is a plain object, without the `get()` and the other helpers of `AxiosHeaders`.

### `InvalidResponseBodyError.response` is the transport's response[](#invalidresponsebodyerrorresponse-is-the-transports-response)

The `response` property carries the [`HttpResponse`](https://docs.apify.com/api/client/js/reference/interface/HttpResponse.md) the transport returned, with the unparsed bytes in `body`, in place of the axios response with the failed body in `data`.

### `ApifyApiError.httpMethod` is uppercase[](#apifyapierrorhttpmethod-is-uppercase)

The method is reported as the client sent it, so `POST` where v2 reported axios's lowercased `post`.

### A `FormData` body is no longer sent[](#a-formdata-body-is-no-longer-sent)

Under v2 axios recognized a `FormData` body and sent it as multipart, taking the boundary from the value itself. The pipeline serializes bodies on its own now and doesn't handle it, so passing one throws a `TypeError` naming the type. Encode it to a `Buffer` or a string with a matching `Content-Type` header. A `Readable`, a `URLSearchParams`, a `Blob` and a `File` all still go through, and so does a web `ReadableStream`.

### A form-encoded object body is encoded by the client[](#a-form-encoded-object-body-is-encoded-by-the-client)

Pairing an object with `Content-Type: application/x-www-form-urlencoded`, which the `contentType` option of `ActorClient.start()`, `call()` and `validateInput()` and of `RunClient.metamorph()` sets, no longer goes through axios. Binary values are base64-encoded wherever they sit in the object, so an `ArrayBuffer` or a typed-array field arrives intact instead of coerced to UTF-8, and a binary field nested under another key keeps its full path instead of losing it. Arrays nested below the top level are sent as `key[]` rather than `key[0]`, which decodes to the same structure.

### `HttpClient` no longer exposes the axios instance[](#httpclient-no-longer-exposes-the-axios-instance)

The `axios`, `httpAgent` and `httpsAgent` properties, the `userProvidedRequestInterceptors` array and the `workflowKey` moved to `AxiosHttpClient` or became internal. The default client has none of them. With an `AxiosHttpClient` plugged in, reach them through `client.httpClient` after narrowing it with `instanceof AxiosHttpClient`. `HttpClient.timeoutMillis` holds the duration of each tier instead of one number, and the cap is in `timeoutMaxMillis`.

The instance itself is bare: the pipeline merges the default headers and serializes the bodies per request, so `AxiosHttpClient.axios` no longer carries the `Authorization`, `X-Apify-Workflow-Key` and `User-Agent` defaults nor the interceptors and the params serializer that serialized requests and parsed responses. A request sent through it directly reaches the API unauthenticated. Go through [`httpClient.call()`](https://docs.apify.com/api/client/js/reference/class/HttpClient.md#call) for an ad-hoc API request.

## Retries[](#retries)

### The error thrown after the retries are exhausted is the last one[](#the-error-thrown-after-the-retries-are-exhausted-is-the-last-one)

`ApifyClient` reports the failure of the final attempt. In v2 `async-retry` reported the error whose message occurred most often across the attempts, so a call that hit five HTTP 500s and then four connection resets threw an `ApifyApiError` for the 500s rather than the reset. Code that branches on `instanceof ApifyApiError` for a call that fails in more than one way may see a different error type than it did before.

### A response body that doesn't parse is no longer retried[](#a-response-body-that-doesnt-parse-is-no-longer-retried)

A successful response whose body doesn't parse as its content type claims throws [`InvalidResponseBodyError`](https://docs.apify.com/api/client/js/reference/class/InvalidResponseBodyError.md) on the first attempt. Under v2 the client retried it, so a key-value store record holding non-JSON text under `application/json` cost every retry before `getRecord()` threw. A connection that drops mid-body still fails as a network error, which is retried.

An error status whose body doesn't parse, such as an HTML page from a proxy with a `502`, throws the [`ApifyApiError`](https://docs.apify.com/api/client/js/reference/class/ApifyApiError.md) subclass for its status code, with the raw body in `message`, and is retried by that status code. Under v2 it threw `InvalidResponseBodyError`.

### The per-attempt timeout grows on a fixed schedule[](#the-per-attempt-timeout-grows-on-a-fixed-schedule)

Each attempt gets the request's timeout doubled once per retry, capped at `timeoutMaxSecs`. In v2 the doubling compounded, because every attempt overwrote the request's timeout with the value it had just computed. A request starting at 5 seconds got 5, 10, 40 and 320 seconds; it now gets 5, 10, 20 and 40. Requests whose timeout is already `timeoutMaxSecs` are unaffected.

### Retry delays are randomized[](#retry-delays-are-randomized)

The wait before a retry is `minDelayBetweenRetriesMillis` doubled once per attempt and then spread over a random factor between one and two, so clients that failed together don't come back at the API in lockstep. The option is a lower bound now rather than the delay itself. At the defaults, a call that burns through all eight retries sleeps 128 to 255 seconds in total, where v2 always slept 128.
