@crawlee/cli 4.0.0-beta.322 → 4.0.0-beta.323
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/commands/upgrade-command.d.ts +19 -0
- package/commands/upgrade-command.js +150 -0
- package/index.js +13 -1
- package/package.json +5 -4
- package/skills/crawlee-upgrade/SKILL.md +20 -0
- package/skills/crawlee-upgrade-v4/SKILL.md +45 -0
- package/skills/crawlee-upgrade-v4/guide/autoscaling.md +256 -0
- package/skills/crawlee-upgrade-v4/guide/browser-management.md +174 -0
- package/skills/crawlee-upgrade-v4/guide/http-clients.md +105 -0
- package/skills/crawlee-upgrade-v4/guide/internals.md +130 -0
- package/skills/crawlee-upgrade-v4/guide/removed-symbols.md +63 -0
- package/skills/crawlee-upgrade-v4/guide/request-loaders.md +241 -0
- package/skills/crawlee-upgrade-v4/guide/sessions-and-proxies.md +164 -0
- package/skills/crawlee-upgrade-v4/guide/statistics.md +56 -0
- package/skills/crawlee-upgrade-v4/guide/storage-backends.md +170 -0
- package/skills/crawlee-upgrade-v4/guide/upgrading-v4.md +1289 -0
- package/skills/crawlee-upgrade-v4/guide/utils-and-types.md +52 -0
|
@@ -0,0 +1,1289 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: upgrading-to-v4
|
|
3
|
+
title: Upgrading to v4
|
|
4
|
+
slug: /upgrading/upgrading-to-v4
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
This page summarizes the breaking changes in Crawlee v4. There are many, so the guide is organized to let you stop reading as early as possible:
|
|
8
|
+
|
|
9
|
+
- [What v4 does better](#what-v4-does-better) — why the migration is worth the trouble.
|
|
10
|
+
- [Upgrade with an AI coding tool](#upgrade-with-an-ai-coding-tool) — generate a migration prompt for your project.
|
|
11
|
+
- [Rename cheat sheet](#rename-cheat-sheet) — the purely mechanical renames, in one table.
|
|
12
|
+
- [Changes most users will hit](#changes-most-users-will-hit) — read this part in full.
|
|
13
|
+
- The **Only if you…** sections — each applies only if you use what its title says. Skim the titles and skip what doesn't concern you. The longer ones only summarize the changes here and link to a separate page with the details.
|
|
14
|
+
- [Appendix: removed symbols](./removed-symbols.md) — for when the compiler hands you a missing name and you want to know where it went.
|
|
15
|
+
|
|
16
|
+
## Upgrade with an AI coding tool
|
|
17
|
+
|
|
18
|
+
The v4 CLI prints a migration prompt for an AI coding tool. Run it with the v4 version of the CLI from the directory of the project you are migrating, then paste the output into a tool that can read your project:
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
npx crawlee@4 upgrade
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
The prompt only contains instructions. They ask the tool to inspect the project, plan, migrate and verify, and to ask once before creating a Git branch and making incremental commits.
|
|
25
|
+
|
|
26
|
+
Adjust the command to your situation:
|
|
27
|
+
|
|
28
|
+
- **Your tool can only read files inside the project.** The prompt links guides in the npx cache. Run `npx crawlee@4 upgrade --export <dir>` to copy them into a directory of your choice and have the prompt link that copy.
|
|
29
|
+
- **The project is a package in a workspace.** Run the command from that package's directory, not the workspace root.
|
|
30
|
+
- **The command cannot tell which major you are on.** It reads the Crawlee runtime dependencies from the nearest `package.json`, preferring installed versions that match the declared ranges. When that is ambiguous, name the starting major: `npx crawlee@4 upgrade --from 3`.
|
|
31
|
+
- **The project already uses v4 and you want to revisit the migration.** Run `npx crawlee@4 upgrade --from 3`.
|
|
32
|
+
- **A bare `crawlee upgrade` says the command does not exist.** A v3 project runs its local v3 CLI, which has no `upgrade`. Use `npx crawlee@4 upgrade`.
|
|
33
|
+
|
|
34
|
+
`--to` defaults to the newest bundled migration, and only v3 to v4 is bundled for now. As guides for later majors are added, the command completes and verifies each major before starting the next, and rejects a path with a missing guide rather than skipping a major.
|
|
35
|
+
|
|
36
|
+
## What v4 does better
|
|
37
|
+
|
|
38
|
+
- **Timeouts that mean what they say.** Navigation and the request handler are [timed separately](#navigation-and-the-request-handler-are-timed-separately) — no more mysteriously summed limits — and a single route can get [its own timeout](#per-route-and-per-request-handler-timeouts) or extend it mid-flight.
|
|
39
|
+
- **Composable crawling context.** The new `extendContext` option and `ContextPipeline` composition replace subclassing tricks for [adding members to the crawling context](#crawling-context-no-longer-includes-a-reference-to-the-crawler-itself).
|
|
40
|
+
- **Bring your own implementation.** Crawlers now accept any [`ISessionPool`](./sessions-and-proxies.md#custom-sessionpool-implementations-via-the-isessionpool-interface), [`IBrowserPool`](./browser-management.md#custom-browserpool-implementations-via-the-ibrowserpool-interface), [`IRenderingTypePredictor`](./browser-management.md#custom-rendering-type-predictors-via-the-irenderingtypepredictor-interface), [`IRequestManager`](./request-loaders.md#request-loaders-and-managers) or [`IStatistics`](./statistics.md#statisticsoptions-is-replaced-by-a-statistics-instance) — and never tear down an instance they did not create, which [`await using` now does for you](#collaborators-you-own-are-disposable).
|
|
41
|
+
- **One concurrency budget for several crawlers.** The new [`ConcurrencySystem`](./autoscaling.md#autoscaling-moved-to-concurrencysystem) can be shared between crawlers, capping their combined concurrency instead of letting each one oversubscribe the host.
|
|
42
|
+
- **Native `fetch` types.** HTTP clients and `context.response` now use the [standard `Response`](#crawlingcontextresponse-is-now-of-type-response), and `got-scraping` is an [opt-in dependency](./http-clients.md#http-client-packages-and-basehttpclient-reshaped) instead of a mandatory one.
|
|
43
|
+
- **The session is the rotation unit.** A session carries its proxy, cookies and error score, and is rotated as a whole when blocked — replacing [proxy tiers](./sessions-and-proxies.md#tieredproxyurls-is-removed-from-proxyconfiguration) and [session rotation counters](#maxsessionrotations-and-requestsessionrotationcount-are-removed).
|
|
44
|
+
- **Crawlers stop stepping on each other.** Multiple crawlers in one process [no longer share the default request queue](#multiple-crawler-instances-use-separate-default-request-queues), and repeated `run()` calls [no longer empty it](#repeated-run-calls-no-longer-empty-the-request-queue) behind your back.
|
|
45
|
+
- **Cookies behave.** `sendRequest` finally [respects your `Cookie` header](#cookie-handling-in-httpcrawler-and-sendrequest), and browser cookies set inside the handler are [persisted to the session](#browser-cookies-are-also-persisted-after-requesthandler).
|
|
46
|
+
- **No half-written results.** Storage writes in a request handler are [transactional](#storage-writes-in-request-handlers-are-transactional) — a handler that throws leaves nothing behind, and its retry does not duplicate data.
|
|
47
|
+
- **Simpler storage backend contract.** A custom storage backend is now [4 classes instead of 7](./storage-backends.md#storagebackend-interface-simplified).
|
|
48
|
+
|
|
49
|
+
## Rename cheat sheet
|
|
50
|
+
|
|
51
|
+
The purely mechanical renames, collected in one place. Where a row links to a section, the rename also comes with a behavior or signature change — read it before renaming blindly.
|
|
52
|
+
|
|
53
|
+
| v3 | v4 |
|
|
54
|
+
| --- | --- |
|
|
55
|
+
| `handleRequestFunction` / `handlePageFunction` | `requestHandler` |
|
|
56
|
+
| `handleRequestTimeoutSecs` | `requestHandlerTimeoutSecs` |
|
|
57
|
+
| `handleFailedRequestFunction` | `failedRequestHandler` |
|
|
58
|
+
| `persistCookiesPerSession` | `saveResponseCookies` |
|
|
59
|
+
| `config` (option / property name) | `configuration` ([details](#config-is-renamed-to-configuration-everywhere)) |
|
|
60
|
+
| `Configuration.getGlobalConfig()` | `Configuration.getGlobalConfiguration()` |
|
|
61
|
+
| `new LocalEventManager(config)` | `LocalEventManager.fromConfiguration(configuration)` |
|
|
62
|
+
| `StorageClient` | `StorageBackend` ([reshaped](./storage-backends.md#storagebackend-interface-simplified)) |
|
|
63
|
+
| `MemoryStorage` (`@crawlee/memory-storage`) | `MemoryStorageBackend` (`@crawlee/core`, [now memory-only](#memorystorage-split-into-filesystemstoragebackend-and-memorystoragebackend)) |
|
|
64
|
+
| `RequestQueueV1` / `RequestQueueV2` / `RequestProvider` | `RequestQueue` |
|
|
65
|
+
| `IRequestList` | `IRequestLoader` ([reshaped](./request-loaders.md#irequestlist-renamed-to-irequestloader)) |
|
|
66
|
+
| `SitemapRequestList` | `SitemapRequestLoader` ([details](./request-loaders.md#sitemaprequestlist-renamed-to-sitemaprequestloader)) |
|
|
67
|
+
| `RobotsFile` | `RobotsTxtFile` |
|
|
68
|
+
| `markRequestHandled()` | `markRequestAsHandled()` |
|
|
69
|
+
| `requestList.length()` / `requestList.handledCount()` | `await getTotalCount()` / `await getHandledCount()` |
|
|
70
|
+
| `requestList.isEmpty()` / `requestList.isFinished()` | `await checkReadiness()` ([details](./request-loaders.md#isempty--isfinished-replaced-by-checkreadiness)) |
|
|
71
|
+
| `dataset.client.listItems()` | `Dataset.getData()` / `Dataset.values()` ([details](./storage-backends.md#datasetclientlistitems-replaced-by-datasetgetdata-and-datasetvalues)) |
|
|
72
|
+
| crawler options `requestList` / `requestQueue` | `requestManager` ([details](./request-loaders.md#crawler-requestlist--requestqueue-options-deprecated-in-favor-of-requestmanager)) |
|
|
73
|
+
| standalone `enqueueLinks({ urls, requestQueue })` | removed; `context.enqueueLinks()` or `addRequests()` ([details](./request-loaders.md#standalone-enqueuelinks-removed-enqueuelinksbyclickingelements-takes-requestmanager)) |
|
|
74
|
+
| `enqueueLinksByClickingElements({ requestQueue })` | `enqueueLinksByClickingElements({ requestManager })` |
|
|
75
|
+
| `enqueueLinks({ globs, regexps, pseudoUrls })` | `enqueueLinks({ include })` ([details](#globs-regexps-and-pseudourls-replaced-by-include)) |
|
|
76
|
+
| `(await enqueueLinks()).processedRequests` | `(await enqueueLinks()).addedRequests` ([details](#enqueuelinks-return-value-reshaped-addrequestsbatchedresult-instead-of-batchaddrequestsresult)) |
|
|
77
|
+
| `autoscaledPoolOptions` | `taskLoopOptions` ([narrowed](./autoscaling.md#autoscaledpooloptions-is-now-taskloopoptions-and-no-longer-carries-concurrency-config)) |
|
|
78
|
+
| `crawler.stats` | `crawler.statistics` ([retyped](./statistics.md#statisticsoptions-is-replaced-by-a-statistics-instance)) |
|
|
79
|
+
| `statistics.state.requestsFinished` (and the other `*Finished*` counters) | `requestsSucceeded` ([details](#finished-request-counters-are-renamed-to-succeeded)) |
|
|
80
|
+
| `statistics.startJob()` / `finishJob()` / `failJob()` | `recordRequestStart()` / `recordRequestSuccess()` / `recordRequestFailure()` ([details](./statistics.md#the-request-recording-methods-are-renamed)) |
|
|
81
|
+
| `browserPoolOptions` | `browserPool` + a `*BrowserPool()` factory ([details](#browserpooloptions-is-removed)) |
|
|
82
|
+
| `gotScraping` (from `@crawlee/utils`) | `GotScrapingHttpClient` (`@crawlee/got-scraping-client`) |
|
|
83
|
+
| `SDK_`-prefixed internal KVS keys | `CRAWLEE_`-prefixed ([details](#internal-kvs-keys-renamed)) |
|
|
84
|
+
| `ArgumentError` (from `ow`) | `ArgumentValidationError` ([details](#argument-validation-errors-use-zod)) |
|
|
85
|
+
|
|
86
|
+
## Changes most users will hit
|
|
87
|
+
|
|
88
|
+
Environment requirements, renamed options and behavior changes that nearly every project runs into. Read this whole section.
|
|
89
|
+
|
|
90
|
+
### ECMAScript modules
|
|
91
|
+
|
|
92
|
+
Crawlee v4 is a native ESM package now. It can be still consumed from a CJS project, as long as you use TypeScript and Node.js version that supports `require(esm)`.
|
|
93
|
+
|
|
94
|
+
### Node 22.13+ required
|
|
95
|
+
|
|
96
|
+
Support for older node versions was dropped.
|
|
97
|
+
|
|
98
|
+
### Actor projects need Apify SDK v4
|
|
99
|
+
|
|
100
|
+
Apify SDK 3.x does not run on `@crawlee/core@4`. Projects that depend on `apify` upgrade to `apify@4` together with Crawlee. The SDK has its own breaking changes to go through after the bump, see its [v4 upgrade guide](https://docs.apify.com/sdk/js/docs/next/upgrading/upgrading-to-v4).
|
|
101
|
+
|
|
102
|
+
### Collaborators you own are disposable
|
|
103
|
+
|
|
104
|
+
A crawler never tears down an instance it did not build, so anything you construct and pass in — `SessionPool`, `ConcurrencySystem`, `BrowserPool`, `RenderingTypePredictor` — is yours to shut down. All of them implement `Symbol.asyncDispose`, so `await using` does it for you:
|
|
105
|
+
|
|
106
|
+
```typescript
|
|
107
|
+
await using concurrencySystem = new ConcurrencySystem({ maxConcurrency: 20 });
|
|
108
|
+
await concurrencySystem.start();
|
|
109
|
+
|
|
110
|
+
await Promise.all([a.run(), b.run()]);
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
The hook calls the same `stop()` / `teardown()` / `destroy()` method as before, and those stay — `await using` needs Node.js 24, and v4 supports Node.js 22.
|
|
114
|
+
|
|
115
|
+
### TypeScript 5.8+ required
|
|
116
|
+
|
|
117
|
+
Support for older TypeScript versions was dropped. Crawlee ships compiled JavaScript, so this only affects type-checking against its type declaration files — plain JavaScript projects are unaffected. In particular, a CJS TypeScript project needs TypeScript 5.8+ to type-check a `require()` of an ESM package like Crawlee; older versions might still work if your project is also ESM.
|
|
118
|
+
|
|
119
|
+
### Cheerio v1
|
|
120
|
+
|
|
121
|
+
Previously, we kept the dependency on cheerio locked to the latest RC version, since there were many breaking changes introduced in v1.0. This release bumps cheerio to the stable v1. `CheerioCrawler`, `HttpCrawler` and `htmlToText` keep parsing with `htmlparser2` through `cheerio/slim`; the `parseWithCheerio` helper on the browser crawlers loads full cheerio, which parses with `parse5`.
|
|
122
|
+
|
|
123
|
+
### Argument validation errors use zod
|
|
124
|
+
|
|
125
|
+
Argument validation moved from `ow` to [zod](https://zod.dev). Invalid inputs now throw `ArgumentValidationError` (previously ow's `ArgumentError`) — update any code catching it by name or `instanceof`.
|
|
126
|
+
|
|
127
|
+
The messages read field-first and name the received type, value, and the validated interface:
|
|
128
|
+
|
|
129
|
+
```text
|
|
130
|
+
// v3 (ow)
|
|
131
|
+
Expected property `maxRequestRetries` to be of type `number` but received type `string` in object `HttpCrawlerOptions`
|
|
132
|
+
|
|
133
|
+
// v4 (zod)
|
|
134
|
+
Invalid input: expected number, received the string `3` at `maxRequestRetries` in `HttpCrawlerOptions`
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Unlike ow, all problems are reported at once (one line per issue), and arrays name their element type:
|
|
138
|
+
|
|
139
|
+
```text
|
|
140
|
+
Invalid input: expected number, received the string `many` at `maxRequestRetries` in `HttpCrawlerOptions`
|
|
141
|
+
Invalid input: expected an array of numbers, received the number `500` at `additionalHttpErrorStatusCodes` in `HttpCrawlerOptions`
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
For programmatic handling, the error exposes zod's structured output — `error.issues` (the [zod issues](https://zod.dev/error-customization) array) and `error.cause` (the raw `ZodError`):
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
try {
|
|
148
|
+
new CheerioCrawler({ maxRequestRetries: '3' } as any);
|
|
149
|
+
} catch (error) {
|
|
150
|
+
if (error instanceof ArgumentValidationError) {
|
|
151
|
+
error.issues[0].path; // ['maxRequestRetries']
|
|
152
|
+
error.cause; // ZodError
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
One behavioral change: options validated against class interfaces (`httpClient`, `configuration`, `eventManager`) now require actual instances (`instanceof BaseHttpClient`, …) rather than duck-typed plain objects — extend the class (or `Object.create(BaseHttpClient.prototype)` in tests) instead of passing an object literal.
|
|
158
|
+
|
|
159
|
+
### Zod 4 required
|
|
160
|
+
|
|
161
|
+
`@crawlee/core` now depends on zod 4, for the codecs it validates persisted state with. Zod is an ordinary dependency rather than a peer, so a project pinned to zod 3 keeps working — it just ends up with both versions installed.
|
|
162
|
+
|
|
163
|
+
### Installing with `--omit=optional` breaks native dependencies
|
|
164
|
+
|
|
165
|
+
Crawlee v4 relies on more native, prebuilt dependencies than v3 did — notably the `impit` HTTP client and the `@crawlee/fs-storage-native` package backing `@crawlee/fs-storage`. Like other napi-rs-based packages, these ship one platform-specific binary per OS/architecture, distributed as `optionalDependencies` so that npm installs only the one matching your platform.
|
|
166
|
+
|
|
167
|
+
Running `npm install --omit=optional` (or the equivalent `yarn`/`pnpm` flag) skips all optional dependencies, including these platform binaries, so the native dependencies fail to install correctly. If your Dockerfile or install scripts carried over `--omit=optional` from a v3 project template, remove it — it is no longer safe to use with Crawlee v4.
|
|
168
|
+
|
|
169
|
+
### Deprecated crawler options are removed
|
|
170
|
+
|
|
171
|
+
The crawler following options are removed:
|
|
172
|
+
|
|
173
|
+
- `handleRequestFunction` -> `requestHandler`
|
|
174
|
+
- `handlePageFunction` -> `requestHandler`
|
|
175
|
+
- `handleRequestTimeoutSecs` -> `requestHandlerTimeoutSecs`
|
|
176
|
+
- `handleFailedRequestFunction` -> `failedRequestHandler`
|
|
177
|
+
|
|
178
|
+
### The `log` crawler option is replaced by `logger`
|
|
179
|
+
|
|
180
|
+
The crawler constructors no longer accept a `log` option with an `@apify/log` `Log` instance. Pass a `logger` implementing the `CrawleeLogger` interface instead. To keep using an `@apify/log` instance (e.g. a `child()` with a custom prefix), wrap it in the `ApifyLogAdapter` from `@crawlee/core`:
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
// v3
|
|
184
|
+
import { CheerioCrawler, log } from 'crawlee';
|
|
185
|
+
|
|
186
|
+
const crawler = new CheerioCrawler({
|
|
187
|
+
log: log.child({ prefix: 'MyCrawler' }),
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
// v4
|
|
191
|
+
import { ApifyLogAdapter, CheerioCrawler, log } from 'crawlee';
|
|
192
|
+
|
|
193
|
+
const crawler = new CheerioCrawler({
|
|
194
|
+
logger: new ApifyLogAdapter(log.child({ prefix: 'MyCrawler' })),
|
|
195
|
+
});
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
Related: `crawler.log` and the crawling context `log` are typed as `CrawleeLogger`, which has no `setLevel()` method - level filtering belongs to the underlying logging library. With the default logger, set the level on the global `@apify/log` instance instead, before constructing the crawler (the crawler's logger copies the level when it is created):
|
|
199
|
+
|
|
200
|
+
```ts
|
|
201
|
+
// v3
|
|
202
|
+
crawler.log.setLevel(LogLevel.DEBUG);
|
|
203
|
+
|
|
204
|
+
// v4
|
|
205
|
+
import log, { LogLevel } from '@apify/log';
|
|
206
|
+
log.setLevel(LogLevel.DEBUG); // before `new CheerioCrawler(...)`
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
### The `utils` bag is removed from the `crawlee` meta-package
|
|
210
|
+
|
|
211
|
+
The `crawlee` meta-package exported a `utils` object — the last remnant of v2's `Apify.utils` namespace — bundling `utils.puppeteer`, `utils.playwright`, `utils.log`, `utils.enqueueLinks`, `utils.social`, `utils.sleep`, `utils.downloadListOfUrls` and `utils.parseOpenGraph`. It is gone. Every member was already exported from `crawlee` under its own name, so the fix is to import that name directly. The exception is `enqueueLinks`: the standalone function is removed too; use `context.enqueueLinks()` in a request handler or `addRequests()` for known URLs:
|
|
212
|
+
|
|
213
|
+
**Before:**
|
|
214
|
+
```typescript
|
|
215
|
+
import { utils } from 'crawlee';
|
|
216
|
+
|
|
217
|
+
await utils.puppeteer.saveSnapshot(page);
|
|
218
|
+
await utils.playwright.blockRequests(page);
|
|
219
|
+
utils.log.info('hello');
|
|
220
|
+
await utils.sleep(1000);
|
|
221
|
+
const emails = utils.social.emailsFromText(text);
|
|
222
|
+
const urls = await utils.downloadListOfUrls({ url });
|
|
223
|
+
const og = await utils.parseOpenGraph(html);
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
**After:**
|
|
227
|
+
```typescript
|
|
228
|
+
import {
|
|
229
|
+
puppeteerUtils,
|
|
230
|
+
playwrightUtils,
|
|
231
|
+
log,
|
|
232
|
+
sleep,
|
|
233
|
+
social,
|
|
234
|
+
downloadListOfUrls,
|
|
235
|
+
parseOpenGraph,
|
|
236
|
+
} from 'crawlee';
|
|
237
|
+
|
|
238
|
+
await puppeteerUtils.saveSnapshot(page);
|
|
239
|
+
await playwrightUtils.blockRequests(page);
|
|
240
|
+
log.info('hello');
|
|
241
|
+
await sleep(1000);
|
|
242
|
+
const emails = social.emailsFromText(text);
|
|
243
|
+
const urls = await downloadListOfUrls({ url });
|
|
244
|
+
const og = await parseOpenGraph(html);
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
Inside a request handler you usually do not need the namespaces at all — `saveSnapshot`, `blockRequests`, `parseWithCheerio`, `infiniteScroll` and friends are already on the crawling context, pre-bound to the current page.
|
|
248
|
+
|
|
249
|
+
### `*Finished*` request counters are renamed to `*Succeeded*`
|
|
250
|
+
|
|
251
|
+
A failed request is also finished, so counters that only ever counted the successful ones were misleading. The rename covers `StatisticState` (`crawler.statistics.state`), the `CalculatedStatistics` returned by `crawler.statistics.calculate()` - which is also what the periodic statistics log line reports - the `FinalStatistics` returned by `crawler.run()`, and the record persisted under `CRAWLEE_CRAWLER_STATISTICS_*`:
|
|
252
|
+
|
|
253
|
+
- `requestsFinished` -> `requestsSucceeded`
|
|
254
|
+
- `requestsFinishedPerMinute` -> `requestsSucceededPerMinute`
|
|
255
|
+
- `requestTotalFinishedDurationMillis` -> `requestTotalSucceededDurationMillis`
|
|
256
|
+
- `requestAvgFinishedDurationMillis` -> `requestAvgSucceededDurationMillis`
|
|
257
|
+
|
|
258
|
+
Tooling that reads the persisted record needs the same rename applied. `crawlerFinishedAt` is unchanged - the crawler really does finish.
|
|
259
|
+
|
|
260
|
+
### Crawler constructors no longer take a `Configuration` argument
|
|
261
|
+
|
|
262
|
+
The crawler classes dropped the optional second `config?: Configuration` constructor parameter: `PlaywrightCrawler`, `PuppeteerCrawler`, and `AdaptivePlaywrightCrawler` (the same applies to the other crawlers). `AdaptivePlaywrightCrawler` additionally now extends `BasicCrawler` rather than `PlaywrightCrawler`. Pass a `Configuration` via the `configuration` option instead (see [Using per-crawler services](#using-per-crawler-services-recommended)).
|
|
263
|
+
|
|
264
|
+
**Before:**
|
|
265
|
+
```typescript
|
|
266
|
+
const crawler = new PlaywrightCrawler({ requestHandler }, new Configuration({ headless: false }));
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
**After:**
|
|
270
|
+
```typescript
|
|
271
|
+
const crawler = new PlaywrightCrawler({
|
|
272
|
+
requestHandler,
|
|
273
|
+
configuration: new Configuration({ headless: false }),
|
|
274
|
+
});
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
`PuppeteerLauncher` keeps its `(launchContext?, configuration?)` constructor signature — this change is only about the crawler classes. `PlaywrightLauncher` is no longer exported at all, see [`PlaywrightLauncher` is no longer exported](./browser-management.md#playwrightlauncher-is-no-longer-exported).
|
|
278
|
+
|
|
279
|
+
### Configuration class redesign
|
|
280
|
+
|
|
281
|
+
The `Configuration` class has been redesigned for v4. The main changes are:
|
|
282
|
+
|
|
283
|
+
#### Direct property access replaces `get()` and `set()`
|
|
284
|
+
|
|
285
|
+
**Before:**
|
|
286
|
+
```typescript
|
|
287
|
+
const config = Configuration.getGlobalConfig();
|
|
288
|
+
config.set('persistStateIntervalMillis', 10_000);
|
|
289
|
+
const headless = config.get('headless');
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
**After:**
|
|
293
|
+
```typescript
|
|
294
|
+
// Configuration is now immutable — set options via the constructor
|
|
295
|
+
const config = new Configuration({ persistStateIntervalMillis: 10_000 });
|
|
296
|
+
const headless = config.headless;
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
The `get()` and `set()` methods are removed. Access config values directly as properties.
|
|
300
|
+
Configuration instances are immutable — attempting to assign a property throws a `TypeError`.
|
|
301
|
+
|
|
302
|
+
#### Constructor options now take precedence over environment variables
|
|
303
|
+
|
|
304
|
+
**New priority order (highest to lowest):**
|
|
305
|
+
1. Constructor options
|
|
306
|
+
2. Environment variables
|
|
307
|
+
3. `crawlee.json`
|
|
308
|
+
4. Schema defaults
|
|
309
|
+
|
|
310
|
+
Previously, environment variables always won. Now `new Configuration({ headless: false })`
|
|
311
|
+
works even when `CRAWLEE_HEADLESS=true` is set.
|
|
312
|
+
|
|
313
|
+
#### Importing Crawlee no longer raises `EventEmitter.defaultMaxListeners`
|
|
314
|
+
|
|
315
|
+
Crawlee no longer sets Node's global `EventEmitter.defaultMaxListeners` to 50 on import. Set it yourself if you relied on it.
|
|
316
|
+
|
|
317
|
+
Each running crawler adds a `SIGINT` listener to `process`, so running more than 10 crawlers at once in the same process now logs a `MaxListenersExceededWarning`. Raise the limit with `process.setMaxListeners()` if you do that.
|
|
318
|
+
|
|
319
|
+
### `KeyValueStore.getInput()` and `Configuration.inputKey` moved to the Apify SDK
|
|
320
|
+
|
|
321
|
+
Reading the run input is an Apify platform concern, so Crawlee no longer has any notion of it:
|
|
322
|
+
|
|
323
|
+
- **`KeyValueStore.getInput()` is removed.** Use `Actor.getInput()` from `apify`, which also handles the platform-assigned input key, encrypted secrets and input schema defaults.
|
|
324
|
+
- **`Configuration.inputKey` and the `CRAWLEE_INPUT_KEY` environment variable are removed.** The Apify SDK's `Configuration` defines `inputKey` itself.
|
|
325
|
+
- **The default key-value store is purged in full**, `INPUT` included. Sparing a key, and claiming a bare `<key>` / `<key>.json` file as the record `<key>` (see [Out-of-band key-value files](#out-of-band-key-value-files-eg-a-hand-placed-inputjson)), is left to subclasses of `FileSystemStorageBackend` through its two protected hooks, `keyValueStoreAdoptionCandidates` and `purgeKeyValueStore`. The Apify SDK's `ApifyFileSystemStorageBackend` does this for its run input; plain Crawlee treats a hand-placed `INPUT.json` as any other file.
|
|
326
|
+
|
|
327
|
+
### Google Sheets sharing links are no longer rewritten
|
|
328
|
+
|
|
329
|
+
`downloadListOfUrls()` and `requestsFromUrl` sources no longer turn a Google Sheets sharing link into the link of its CSV export. `Actor.getInput()` from `apify` does this for the Actor input now; elsewhere, use the CSV export link (`https://docs.google.com/spreadsheets/d/<id>/gviz/tq?tqx=out:csv`) directly.
|
|
330
|
+
|
|
331
|
+
### Service management moved from `Configuration` to `ServiceLocator`
|
|
332
|
+
|
|
333
|
+
The service management functionality has been extracted from `Configuration` into a new `ServiceLocator` class.
|
|
334
|
+
|
|
335
|
+
#### Breaking changes
|
|
336
|
+
|
|
337
|
+
The following methods and properties have been removed from `Configuration`:
|
|
338
|
+
|
|
339
|
+
- `Configuration.getStorageClient()` - moved to `ServiceLocator.getStorageBackend()`
|
|
340
|
+
- `Configuration.getEventManager()` - moved to `ServiceLocator.getEventManager()`
|
|
341
|
+
- `Configuration.useStorageClient()` - use `ServiceLocator.setStorageBackend()` instead
|
|
342
|
+
- `Configuration.useEventManager()` - use `ServiceLocator.setEventManager()` instead
|
|
343
|
+
|
|
344
|
+
The setters are stricter than the methods they replace. `Configuration.useStorageClient()` swapped the client at any time; `setStorageBackend()`, `setEventManager()` and `setConfiguration()` throw a `ServiceConflictError` once a different instance is in place — including the default one the locator creates the first time a getter runs. Set your services before anything opens a storage or constructs a crawler.
|
|
345
|
+
- `Configuration.resetGlobalState()` - use `serviceLocator.reset()` instead. The method is marked `@internal`: it exists at runtime and is the supported way to tear down global state between tests, but it is not part of the public API and may change without a major version bump.
|
|
346
|
+
- `Configuration.storageManagers` - use `serviceLocator.getStorageInstanceManager()` instead. Also marked `@internal` - available at runtime, but excluded from the documented surface and not covered by semver guarantees. Application code should reach storages through `Dataset.open()` / `KeyValueStore.open()` / `RequestQueue.open()` rather than the instance manager.
|
|
347
|
+
|
|
348
|
+
The `EventManager` and `LocalEventManager` constructors now accept an options object for configuring event intervals (e.g. `persistStateIntervalMillis`, `systemInfoIntervalMillis`). You can also use the new `LocalEventManager.fromConfiguration()` factory method to create an instance with intervals derived from a `Configuration` object.
|
|
349
|
+
|
|
350
|
+
#### Migration guide
|
|
351
|
+
|
|
352
|
+
If you were using the removed `Configuration` methods directly, you need to update your code:
|
|
353
|
+
|
|
354
|
+
**Before:**
|
|
355
|
+
```typescript
|
|
356
|
+
import { Configuration } from 'crawlee';
|
|
357
|
+
|
|
358
|
+
const config = Configuration.getGlobalConfig();
|
|
359
|
+
const storageBackend = config.getStorageClient();
|
|
360
|
+
const eventManager = config.getEventManager();
|
|
361
|
+
|
|
362
|
+
// or static methods
|
|
363
|
+
const storageBackend = Configuration.getStorageClient();
|
|
364
|
+
// (both of these are the removed v3 APIs)
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
**After:**
|
|
368
|
+
```typescript
|
|
369
|
+
import { serviceLocator } from 'crawlee';
|
|
370
|
+
|
|
371
|
+
const storageBackend = serviceLocator.getStorageBackend();
|
|
372
|
+
const eventManager = serviceLocator.getEventManager();
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
#### Using per-crawler services (recommended)
|
|
376
|
+
|
|
377
|
+
The new `ServiceLocator` supports per-crawler service isolation, allowing you to use different storage backends or event managers for different crawlers by passing them via options:
|
|
378
|
+
|
|
379
|
+
```typescript
|
|
380
|
+
import { BasicCrawler, Configuration, LocalEventManager, MemoryStorageBackend } from 'crawlee';
|
|
381
|
+
|
|
382
|
+
const crawler = new BasicCrawler({
|
|
383
|
+
requestHandler: async ({ request, log }) => {
|
|
384
|
+
log.info(`Processing ${request.url}`);
|
|
385
|
+
},
|
|
386
|
+
configuration: new Configuration({ headless: false }),
|
|
387
|
+
storageBackend: new MemoryStorageBackend(),
|
|
388
|
+
eventManager: LocalEventManager.fromConfiguration(),
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
await crawler.run(['https://example.com']);
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
#### Using the global service locator
|
|
395
|
+
|
|
396
|
+
For most use cases, the global `serviceLocator` singleton works well:
|
|
397
|
+
|
|
398
|
+
```typescript
|
|
399
|
+
import { serviceLocator, BasicCrawler, MemoryStorageBackend } from 'crawlee';
|
|
400
|
+
|
|
401
|
+
// Configure global services (optional)
|
|
402
|
+
serviceLocator.setStorageBackend(new MemoryStorageBackend());
|
|
403
|
+
|
|
404
|
+
// All crawlers will use the global service locator by default
|
|
405
|
+
const crawler = new BasicCrawler({
|
|
406
|
+
requestHandler: async ({ request, log }) => {
|
|
407
|
+
log.info(`Processing ${request.url}`);
|
|
408
|
+
},
|
|
409
|
+
});
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
#### Accessing configuration
|
|
413
|
+
|
|
414
|
+
`Configuration.getGlobalConfiguration()` remains as a utility function, but in most cases, you should use `serviceLocator.getConfiguration()` instead:
|
|
415
|
+
|
|
416
|
+
```typescript
|
|
417
|
+
import { serviceLocator } from 'crawlee';
|
|
418
|
+
|
|
419
|
+
const config = serviceLocator.getConfiguration();
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
Despite its name, `getGlobalConfiguration()` returns the configuration of the currently active service locator, which is not always the global one — prefer `serviceLocator.getConfiguration()`.
|
|
423
|
+
|
|
424
|
+
#### `config` is renamed to `configuration` everywhere
|
|
425
|
+
|
|
426
|
+
v3 used `config` and `configuration` interchangeably. v4 settles on `configuration`.
|
|
427
|
+
|
|
428
|
+
Renamed methods:
|
|
429
|
+
|
|
430
|
+
| Before | After |
|
|
431
|
+
| --- | --- |
|
|
432
|
+
| `Configuration.getGlobalConfig()` | `Configuration.getGlobalConfiguration()` |
|
|
433
|
+
| `new LocalEventManager(config)` | `LocalEventManager.fromConfiguration(configuration)` |
|
|
434
|
+
|
|
435
|
+
Renamed options — pass `configuration` instead of `config`:
|
|
436
|
+
|
|
437
|
+
- `Dataset.open()`, `KeyValueStore.open()` and `RequestQueue.open()` (`StorageOpenOptions`)
|
|
438
|
+
- `useState()` (`UseStateOptions`)
|
|
439
|
+
- `purgeDefaultStorages()` (both the options object and the legacy positional argument)
|
|
440
|
+
- `saveSnapshot()` in `@crawlee/playwright` and `@crawlee/puppeteer` (`SaveSnapshotOptions`)
|
|
441
|
+
- `RecoverableStateOptions` and `RequestListOptions`
|
|
442
|
+
|
|
443
|
+
`CpuLoadSignalOptions` and `MemoryLoadSignalOptions` no longer take a configuration at all — drop the `config` field.
|
|
444
|
+
|
|
445
|
+
**Before:**
|
|
446
|
+
```typescript
|
|
447
|
+
const store = await KeyValueStore.open(null, { config: new Configuration({ persistStorage: false }) });
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
**After:**
|
|
451
|
+
```typescript
|
|
452
|
+
const store = await KeyValueStore.open(null, { configuration: new Configuration({ persistStorage: false }) });
|
|
453
|
+
```
|
|
454
|
+
|
|
455
|
+
Renamed properties — `Dataset.config`, `KeyValueStore.config` and `BrowserLauncher.config` (including `PuppeteerLauncher`) are now `.configuration`. The `config` property of the crawlers, `RequestQueue`, `SessionPool` and `EventManager` is removed without a `.configuration` counterpart; use `serviceLocator.getConfiguration()`.
|
|
456
|
+
|
|
457
|
+
The `configuration` crawler option is unchanged, as are `serviceLocator.getConfiguration()` and `serviceLocator.setConfiguration()`.
|
|
458
|
+
|
|
459
|
+
### Navigation and the request handler are timed separately
|
|
460
|
+
|
|
461
|
+
In v3, navigation ran inside the request handler's time window, and the two options were summed (plus an undocumented 10 second buffer) to form the actual limit. Setting `requestHandlerTimeoutSecs: 60` on a `PlaywrightCrawler` therefore produced errors complaining about 130 seconds.
|
|
462
|
+
|
|
463
|
+
Navigation and the request handler are now timed independently, and each reports itself:
|
|
464
|
+
|
|
465
|
+
| Option | Covers | Default |
|
|
466
|
+
| --- | --- | --- |
|
|
467
|
+
| `requestHandlerTimeoutSecs` | your `requestHandler` only | 60 |
|
|
468
|
+
| `navigationTimeoutSecs` | the `preNavigationHooks`, the navigation, and the `postNavigationHooks` together | 30 (HTTP), 60 (browser) |
|
|
469
|
+
|
|
470
|
+
`navigationTimeoutSecs` is a single budget shared by the whole navigation phase, so a slow hook eats into the same window the navigation uses.
|
|
471
|
+
|
|
472
|
+
Two things to watch for when upgrading:
|
|
473
|
+
|
|
474
|
+
- **Navigation hooks are now bounded.** They had no timeout of their own before, so a `preNavigationHooks` / `postNavigationHooks` function that pushes the whole phase past `navigationTimeoutSecs` will now fail the request. Raise `navigationTimeoutSecs`, or call `context.extendTimeout()` from inside the hook when the extra time is only needed occasionally.
|
|
475
|
+
- **A request can no longer hang forever.** An internal timeout now bounds the whole request, covering the phases that have no timeout of their own (`extendContext`, the robots.txt check, response processing). By default it is deliberately generous (twice the request handler timeout, and never less than 5 minutes), so it only fires when a request is genuinely stuck. Set `CRAWLEE_INTERNAL_TIMEOUT` (in milliseconds) to override it. A value below the navigation and request handler timeouts is ignored — the crawler warns at startup and keeps the timeout above them so those phases are never cut short.
|
|
476
|
+
|
|
477
|
+
### Per-route and per-request handler timeouts
|
|
478
|
+
|
|
479
|
+
`requestHandlerTimeoutSecs` still applies to every request alike, but a single route can now opt out of it — useful when one page type needs markedly more time than the rest, and you do not want to raise the timeout for everything else to accommodate it:
|
|
480
|
+
|
|
481
|
+
```typescript
|
|
482
|
+
router.addHandler('LIST', async ({ enqueueLinks }) => { ... }, { requestHandlerTimeoutSecs: 120 });
|
|
483
|
+
router.addHandler('DETAIL', async ({ pushData }) => { ... }); // keeps the crawler's default
|
|
484
|
+
```
|
|
485
|
+
|
|
486
|
+
When the time needed is only apparent once the handler is already running, `context.extendTimeout()` buys it more:
|
|
487
|
+
|
|
488
|
+
```typescript
|
|
489
|
+
router.addHandler('LIST', async ({ page, extendTimeout }) => {
|
|
490
|
+
const pageCount = await countPages(page);
|
|
491
|
+
extendTimeout(pageCount * 10);
|
|
492
|
+
await scrapeAllPages(page);
|
|
493
|
+
});
|
|
494
|
+
```
|
|
495
|
+
|
|
496
|
+
### `useSessionPool` and `sessionPoolOptions` are removed
|
|
497
|
+
|
|
498
|
+
The `useSessionPool` and `sessionPoolOptions` options have been removed from the `BasicCrawler` constructor. Every crawler now uses a `SessionPool` by default. Instead of passing `sessionPoolOptions`, create a `SessionPool` instance directly and pass it via the `sessionPool` option.
|
|
499
|
+
|
|
500
|
+
```typescript
|
|
501
|
+
import { SessionPool } from '@crawlee/basic';
|
|
502
|
+
|
|
503
|
+
const crawler = new BasicCrawler({
|
|
504
|
+
// The old parameters won't work anymore
|
|
505
|
+
// useSessionPool: true,
|
|
506
|
+
// sessionPoolOptions: { maxUsageCount: 5 },
|
|
507
|
+
sessionPool: new SessionPool({
|
|
508
|
+
sessionOptions: { maxUsageCount: 5 },
|
|
509
|
+
}),
|
|
510
|
+
});
|
|
511
|
+
```
|
|
512
|
+
|
|
513
|
+
When a `sessionPool` is supplied, the crawler ignores its `proxyConfiguration` option (with a warning), so a crawler that combined `sessionPoolOptions` with `proxyConfiguration` would silently stop using proxies. Assign the proxies in the pool's `createSessionFunction` instead:
|
|
514
|
+
|
|
515
|
+
```typescript
|
|
516
|
+
import { Session, SessionPool } from '@crawlee/basic';
|
|
517
|
+
|
|
518
|
+
const crawler = new BasicCrawler({
|
|
519
|
+
// proxyConfiguration is not passed to the crawler anymore
|
|
520
|
+
sessionPool: new SessionPool({
|
|
521
|
+
sessionOptions: { maxUsageCount: 5 },
|
|
522
|
+
createSessionFunction: async (opts) =>
|
|
523
|
+
new Session({
|
|
524
|
+
...opts?.sessionOptions,
|
|
525
|
+
proxyInfo: await proxyConfiguration.newProxyInfo(opts?.sessionOptions?.proxyInfo),
|
|
526
|
+
}),
|
|
527
|
+
}),
|
|
528
|
+
});
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
### `SessionPool` is now lazy-initialized
|
|
532
|
+
|
|
533
|
+
`SessionPool.open()` static factory method is removed. Create instances with `new SessionPool(options)` instead — all public methods automatically initialize the pool on first use.
|
|
534
|
+
|
|
535
|
+
`SessionPool.usableSessionsCount` and `SessionPool.retiredSessionsCount` are now async methods instead of synchronous getters.
|
|
536
|
+
|
|
537
|
+
**Before:**
|
|
538
|
+
```typescript
|
|
539
|
+
const sessionPool = await SessionPool.open({ maxPoolSize: 100 });
|
|
540
|
+
const count = sessionPool.usableSessionsCount;
|
|
541
|
+
```
|
|
542
|
+
|
|
543
|
+
**After:**
|
|
544
|
+
```typescript
|
|
545
|
+
const sessionPool = new SessionPool({ maxPoolSize: 100 });
|
|
546
|
+
const count = await sessionPool.usableSessionsCount();
|
|
547
|
+
```
|
|
548
|
+
|
|
549
|
+
### `SessionPool.persistState()`, `resetStore()` and `teardown()` no longer take options
|
|
550
|
+
|
|
551
|
+
The `PersistenceOptions` argument of `persistState()` and `resetStore()` and the `{ persistState }` argument of `teardown()` are removed. They overrode the pool's `persistenceOptions` for a single call; the pool's own `persistenceOptions` now always decide whether the state is written, so there is nothing to replace them with.
|
|
552
|
+
|
|
553
|
+
`resetStore()` now throws while the pool is running, since the next periodic write would put the record straight back. Call `teardown()` first, or use the new `reset()` to discard the in-memory sessions instead.
|
|
554
|
+
|
|
555
|
+
### `RequestList` prefers the persisted record over the `state` option
|
|
556
|
+
|
|
557
|
+
With both `state` and `persistStateKey` set, the record now wins. Previously `state` did. The option is also validated up front: `nextIndex` must be a non-negative integer and `inProgress` an array of unique keys. The `@internal` `isStatePersisted` flag is gone.
|
|
558
|
+
|
|
559
|
+
Both `SessionPool` and `RequestList` now persist through `RecoverableState`, like `Statistics`. Resuming a v3 crawl on v4 is not supported: `RequestList` stores its records under `CRAWLEE_`-prefixed keys where v3 used `SDK_`, so a v4 run does not find a v3 run's state and starts the list from the beginning. Finish or discard in-flight crawls before upgrading.
|
|
560
|
+
|
|
561
|
+
### `retireOnBlockedStatusCodes` is removed from `Session`
|
|
562
|
+
|
|
563
|
+
`Session.retireOnBlockedStatusCodes` is removed. Blocked status code handling is now internal to the crawler. Configure blocked status codes via the `blockedStatusCodes` crawler option (moved from `sessionPoolOptions`).
|
|
564
|
+
|
|
565
|
+
### `maxSessionRotations` and `request.sessionRotationCount` are removed
|
|
566
|
+
|
|
567
|
+
Session errors no longer have their own retry budget. The `maxSessionRotations` crawler option, the `Request.sessionRotationCount` property, and the special-case retry logic for `SessionError` are all gone. A `SessionError` now retires the session and counts toward `maxRequestRetries` like any other failure, so configure a single retry limit via `maxRequestRetries` (default `3`). `SessionError` also no longer extends `RetryRequestError` — if you were catching `RetryRequestError` to detect a session-triggered retry, branch on `SessionError` directly instead.
|
|
568
|
+
|
|
569
|
+
### Cookie handling in `HttpCrawler` and `sendRequest`
|
|
570
|
+
|
|
571
|
+
Cookie handling was refactored to be simpler and more predictable. The `BaseHttpClient` is now the single place where the `Cookie` request header is assembled, by merging cookies from the session's cookie jar with any `Cookie` header already present on the request. Explicit `Cookie` headers take precedence over jar cookies with the same name.
|
|
572
|
+
|
|
573
|
+
This means `sendRequest` now respects user-provided cookies. In v3, passing a `Cookie` header via `sendRequest` headers was silently overwritten by the session's cookie jar — this is no longer the case.
|
|
574
|
+
|
|
575
|
+
The precedence (highest to lowest) is:
|
|
576
|
+
|
|
577
|
+
1. `sendRequest` `Cookie` header and `cookieJar` overrides
|
|
578
|
+
2. `Cookie` header set directly on the request (via `request.headers`)
|
|
579
|
+
3. Session cookie jar (persisted cookies received from `Set-Cookie` response headers or set manually)
|
|
580
|
+
|
|
581
|
+
To fully replace the cookie jar for a `sendRequest` call, pass a custom `cookieJar` in the options:
|
|
582
|
+
|
|
583
|
+
```typescript
|
|
584
|
+
import { CookieJar } from 'tough-cookie';
|
|
585
|
+
|
|
586
|
+
const jar = new CookieJar();
|
|
587
|
+
await jar.setCookie('my=cookie', request.url);
|
|
588
|
+
const response = await sendRequest({ url: '...' }, { cookieJar: jar });
|
|
589
|
+
```
|
|
590
|
+
|
|
591
|
+
The protected `HttpCrawler._applyCookies` method is removed. If you were overriding it in a subclass, move your logic to a `preNavigationHook` that sets cookies on `request.headers.Cookie` or on the `session` cookie jar directly.
|
|
592
|
+
|
|
593
|
+
`mergeCookies` now skips malformed cookie fragments with a warning instead of throwing.
|
|
594
|
+
|
|
595
|
+
#### `Session.getCookies`, `setCookies` and `setCookiesFromResponse` are removed
|
|
596
|
+
|
|
597
|
+
The public cookie helper methods on `Session` — `getCookies(url)`, `setCookies(cookies, url)`, and `setCookiesFromResponse(response)` — have been removed as part of centralizing cookie assembly in `BaseHttpClient`. Work with the session's `cookieJar` directly, or use `Session.getCookieString(url)` to read the assembled `Cookie` header value. `Session.getCookieString()` and `Session.setCookie()` are now async, so `await` existing calls. Both exist only on the `Session` class; the crawling context's `session` is typed as `ISession`, so use its `cookieJar` there.
|
|
598
|
+
|
|
599
|
+
**Before:**
|
|
600
|
+
```typescript
|
|
601
|
+
const cookies = session.getCookies(url);
|
|
602
|
+
session.setCookies([{ name: 'foo', value: 'bar' }], url);
|
|
603
|
+
session.setCookiesFromResponse(response);
|
|
604
|
+
```
|
|
605
|
+
|
|
606
|
+
**After:**
|
|
607
|
+
```typescript
|
|
608
|
+
// Read the Cookie header string for a URL (on a `Session` instance):
|
|
609
|
+
const cookieHeader = await session.getCookieString(url);
|
|
610
|
+
|
|
611
|
+
// Set / read cookies via the jar directly:
|
|
612
|
+
await session.cookieJar.setCookie('foo=bar', url);
|
|
613
|
+
const cookieHeader2 = await session.cookieJar.getCookieString(url);
|
|
614
|
+
```
|
|
615
|
+
|
|
616
|
+
### `persistCookiesPerSession` renamed to `saveResponseCookies`
|
|
617
|
+
|
|
618
|
+
The `persistCookiesPerSession` crawler option has been renamed to `saveResponseCookies` on both `HttpCrawler` (and its subclasses like `CheerioCrawler`, `JSDOMCrawler`, etc.) and `BrowserCrawler`. When enabled (the default), response cookies are stored in the session's cookie jar so they're sent on subsequent requests using the same session. Rename the option in your crawler constructor options to migrate.
|
|
619
|
+
|
|
620
|
+
### Browser cookies are also persisted after `requestHandler`
|
|
621
|
+
|
|
622
|
+
Previously, `BrowserCrawler` with `saveResponseCookies` (formerly `persistCookiesPerSession`) only copied cookies from the page into the session after navigation and **before** `requestHandler` ran. Cookies set during the handler — login flows, `page.setCookie()`, or XHR/`fetch` `Set-Cookie` responses — were not stored on the session for later requests.
|
|
623
|
+
|
|
624
|
+
In v4, when `saveResponseCookies` is enabled (the default), browser cookies are also re-read and stored in the session cookie jar **after** `requestHandler` completes. If you relied on handler-set cookies staying page-local and not affecting later requests on the same session, set `saveResponseCookies: false` or clear/overwrite cookies on the session explicitly.
|
|
625
|
+
|
|
626
|
+
### `browserPoolOptions` is removed
|
|
627
|
+
|
|
628
|
+
`browserPoolOptions` is gone from every browser crawler. It was a second way of configuring the very pool that the `browserPool` option accepts, and the two could not be combined — passing a pool made the options silently disappear.
|
|
629
|
+
|
|
630
|
+
Build the pool with the factory that matches your crawler instead. Each factory takes every `BrowserPool` option plus the crawler's own `launchContext`, `headless` and `remoteBrowser` (`stagehandOptions` in place of `remoteBrowser` for `stagehandBrowserPool()`), and derives the browser plugin from them, so the pool can never mismatch the crawler it is passed to:
|
|
631
|
+
|
|
632
|
+
| crawler | factory |
|
|
633
|
+
| --- | --- |
|
|
634
|
+
| `PlaywrightCrawler` | `playwrightBrowserPool()` |
|
|
635
|
+
| `PuppeteerCrawler` | `puppeteerBrowserPool()` |
|
|
636
|
+
| `StagehandCrawler` | `stagehandBrowserPool()` |
|
|
637
|
+
|
|
638
|
+
**Before:**
|
|
639
|
+
```typescript
|
|
640
|
+
const crawler = new PlaywrightCrawler({
|
|
641
|
+
browserPoolOptions: { useFingerprints: false },
|
|
642
|
+
launchContext: { launcher: firefox },
|
|
643
|
+
});
|
|
644
|
+
```
|
|
645
|
+
|
|
646
|
+
**After:**
|
|
647
|
+
```typescript
|
|
648
|
+
const crawler = new PlaywrightCrawler({
|
|
649
|
+
browserPool: playwrightBrowserPool({
|
|
650
|
+
useFingerprints: false,
|
|
651
|
+
launchContext: { launcher: firefox },
|
|
652
|
+
}),
|
|
653
|
+
});
|
|
654
|
+
```
|
|
655
|
+
|
|
656
|
+
Building the pool outside the crawler has one consequence worth knowing: a pool passed as `browserPool` is borrowed, so the crawler never destroys it, and the options that would have configured a pool of the crawler's own — `launchContext`, `headless`, `remoteBrowser` and, for `StagehandCrawler`, `stagehandOptions` — are now **rejected** instead of silently ignored. Move them into the factory call.
|
|
657
|
+
|
|
658
|
+
`remoteBrowser` keeps working on its own for the terse case; pass the same `remoteBrowser` to the factory when you also want to tune the pool, or to share one remote pool between crawlers. Remote connections are owned by the `RemotePlaywrightPlugin` / `RemotePuppeteerPlugin` classes from `@crawlee/browser-pool` — there is no separate `RemoteBrowserPool`; `BrowserPool` itself accepts `maxOpenBrowsers`. `StagehandCrawler` does not support `remoteBrowser` (it throws) — Stagehand manages its own browser via `stagehandOptions.env`.
|
|
659
|
+
|
|
660
|
+
`headless` is now declared on each concrete crawler rather than on `BrowserCrawler`, so the puppeteer-only `'new'` and `'old'` values are only accepted by `PuppeteerCrawler`.
|
|
661
|
+
|
|
662
|
+
### `ignoreSslErrors` is renamed to `ignoreTlsErrors` and defaults to `false`
|
|
663
|
+
|
|
664
|
+
The crawler option is renamed to `ignoreTlsErrors`, matching the naming used everywhere else in v4 (`session.proxyInfo.ignoreTlsErrors`, the browser pool, the impit client). The old `ignoreSslErrors` name is no longer accepted — rename it in your crawler options.
|
|
665
|
+
|
|
666
|
+
The default also changed from `true` to `false`: HTTP crawlers now verify TLS certificates and fail requests to sites with invalid ones. Set `ignoreTlsErrors: true` to restore the v3 behavior. `FileDownload` takes the same option with the same default; see [its section](#filedownload-now-extends-basiccrawler-and-takes-a-slimmer-filedownloadoptions).
|
|
667
|
+
|
|
668
|
+
Under the hood the crawler now forwards the option to the HTTP client as `SendRequestOptions.ignoreTlsErrors` on every navigation request, and the same flag is enabled automatically for MITM proxy sessions (`session.proxyInfo.ignoreTlsErrors`), matching the browser crawlers.
|
|
669
|
+
|
|
670
|
+
This only affects custom `BaseHttpClient` implementations: honor `ignoreTlsErrors` (from `SendRequestOptions`, or `CustomFetchOptions` when extending the `BaseHttpClient` class from `@crawlee/http-client`) if your client can disable TLS verification. The built-in impit and got-scraping clients do; the native fetch fallback cannot, so it warns and ignores the flag.
|
|
671
|
+
|
|
672
|
+
### `preNavigationHooks` in `HttpCrawler` no longer accepts `gotOptions` object
|
|
673
|
+
|
|
674
|
+
The `preNavigationHooks` option in `HttpCrawler` subclasses no longer accepts the `gotOptions` object as a second parameter. Modify the `crawlingContext` fields (e.g. `.request`) directly instead.
|
|
675
|
+
|
|
676
|
+
### Browser navigation hooks no longer receive `gotoOptions` as a second argument
|
|
677
|
+
|
|
678
|
+
The `preNavigationHooks` and `postNavigationHooks` of the browser crawlers (`PlaywrightCrawler`, `PuppeteerCrawler`) received the options object forwarded to `page.goto()` as a second parameter in v3. The hooks now receive only the crawling context, and the `page.goto()` options are available as its `gotoOptions` member, which can be mutated in place:
|
|
679
|
+
|
|
680
|
+
```ts
|
|
681
|
+
// v3
|
|
682
|
+
preNavigationHooks: [
|
|
683
|
+
async (crawlingContext, gotoOptions) => {
|
|
684
|
+
gotoOptions.timeout = 60_000;
|
|
685
|
+
},
|
|
686
|
+
],
|
|
687
|
+
|
|
688
|
+
// v4
|
|
689
|
+
preNavigationHooks: [
|
|
690
|
+
async ({ gotoOptions }) => {
|
|
691
|
+
gotoOptions.timeout = 60_000;
|
|
692
|
+
},
|
|
693
|
+
],
|
|
694
|
+
```
|
|
695
|
+
|
|
696
|
+
### `handleCloudflareChallenge` hooks must return the response
|
|
697
|
+
|
|
698
|
+
In v3, calling `handleCloudflareChallenge()` in a `postNavigationHooks` entry was enough on its own - the helper received the session and removed `403` from the session pool's blocked status codes, so the challenge page (which is served with a 403 status) did not trip the blocked-request detection.
|
|
699
|
+
|
|
700
|
+
In v4, blocked status code handling is internal to the crawler and runs *after* the post-navigation hooks, and the helper no longer touches it. Instead, `handleCloudflareChallenge()` returns the reloaded `Response` after solving the challenge, and the hook must return it as the new context response - otherwise the crawler still sees the original 403 challenge response and throws a `SessionError` before your `requestHandler` runs, even when the challenge was solved successfully.
|
|
701
|
+
|
|
702
|
+
Use the pre-wrapped `handleCloudflareChallengeHook()` (it also handles the no-challenge case), or return the response yourself:
|
|
703
|
+
|
|
704
|
+
```ts
|
|
705
|
+
// v3
|
|
706
|
+
postNavigationHooks: [
|
|
707
|
+
async ({ handleCloudflareChallenge }) => {
|
|
708
|
+
await handleCloudflareChallenge();
|
|
709
|
+
},
|
|
710
|
+
],
|
|
711
|
+
|
|
712
|
+
// v4
|
|
713
|
+
import { handleCloudflareChallengeHook } from 'crawlee';
|
|
714
|
+
|
|
715
|
+
postNavigationHooks: [handleCloudflareChallengeHook()],
|
|
716
|
+
|
|
717
|
+
// v4 (manual equivalent)
|
|
718
|
+
postNavigationHooks: [
|
|
719
|
+
async ({ handleCloudflareChallenge }) => {
|
|
720
|
+
// Returning `{ response: undefined }` would clobber the navigation response
|
|
721
|
+
// when there was no challenge, so only return it when one was solved.
|
|
722
|
+
const response = await handleCloudflareChallenge();
|
|
723
|
+
return response && { response };
|
|
724
|
+
},
|
|
725
|
+
],
|
|
726
|
+
```
|
|
727
|
+
|
|
728
|
+
If you called the standalone `playwrightUtils.handleCloudflareChallenge(page, url, session, options)` directly, note that the `session` parameter is gone - the v4 signature is `handleCloudflareChallenge(page, url, options?, response?)`, so an options object left in the old fourth position would be taken for the navigation response instead of being applied.
|
|
729
|
+
|
|
730
|
+
### Removed crawling context properties
|
|
731
|
+
|
|
732
|
+
#### Crawling context no longer includes Error for failed requests
|
|
733
|
+
|
|
734
|
+
The crawling context no longer includes the `Error` object for failed requests. Use the second parameter of the `errorHandler` or `failedRequestHandler` callbacks to access the error.
|
|
735
|
+
|
|
736
|
+
#### Crawling context no longer includes a reference to the crawler itself
|
|
737
|
+
|
|
738
|
+
This was previously accessible via `context.crawler`. If you want to restore the functionality, you may use the `extendContext` option of the crawler:
|
|
739
|
+
|
|
740
|
+
```typescript
|
|
741
|
+
const crawler = new CheerioCrawler({
|
|
742
|
+
// The return type annotation is required: without it TypeScript cannot infer `crawler` from its own initializer.
|
|
743
|
+
extendContext: (): { crawler: Pick<CheerioCrawler, 'stop'> } => ({ crawler }),
|
|
744
|
+
requestHandler: async (context) => {
|
|
745
|
+
if (Math.random() < 0.01) {
|
|
746
|
+
context.crawler.stop()
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
})
|
|
750
|
+
```
|
|
751
|
+
|
|
752
|
+
`extendContext` runs **before navigation**, so the members it returns are visible to the `preNavigationHooks`, `postNavigationHooks`, and the `requestHandler` alike. As a consequence, the `context` passed to `extendContext` is the pre-navigation context and does **not** include navigation-dependent members (e.g. `page`, `response`, `$`, `body`). If your extension needs to read those, do it in a `postNavigationHook` or the `requestHandler` instead.
|
|
753
|
+
|
|
754
|
+
#### Crawling context no longer includes `closeCookieModals`
|
|
755
|
+
|
|
756
|
+
The `closeCookieModals` context helper is removed from the Playwright and Puppeteer crawlers, along with the `playwrightUtils.closeCookieModals` / `puppeteerUtils.closeCookieModals` functions and the optional `idcac-playwright` peer dependency they were built on.
|
|
757
|
+
|
|
758
|
+
See the [cookie modals guide](https://crawlee.dev/js/docs/next/guides/cookie-modals) for the replacements, including a drop-in `preNavigationHook` built on `@duckduckgo/autoconsent`.
|
|
759
|
+
|
|
760
|
+
### Crawling context is strictly typed
|
|
761
|
+
|
|
762
|
+
Previously, the crawling context extended a `Record` type, allowing to access any property. This was changed to a strict type, which means that you can only access properties that are defined in the context.
|
|
763
|
+
|
|
764
|
+
### The default HTTP client is now `impit`
|
|
765
|
+
|
|
766
|
+
The HTTP crawlers (and `sendRequest`) no longer use `got-scraping` by default. The default client is now `ImpitHttpClient` from the optional `@crawlee/impit-client` package (a Rust-based client with TLS fingerprint impersonation); when it is not installed, the crawlers fall back to a plain `fetch`-based client with a logged warning (no proxy support or impersonation). To keep using `got-scraping`, install `@crawlee/got-scraping-client` and pass `httpClient: new GotScrapingHttpClient()` explicitly.
|
|
767
|
+
|
|
768
|
+
Note that the session's fingerprint drives the impersonation: each new session gets a randomized realistic fingerprint by default, and its `browser` hint picks the browser `impit` impersonates. A `browser` option passed to the `ImpitHttpClient` constructor overrides that hint for every session and logs a warning. To force a specific browser family, leave the option unset and pin the fingerprint on the sessions instead:
|
|
769
|
+
|
|
770
|
+
```ts
|
|
771
|
+
const crawler = new CheerioCrawler({
|
|
772
|
+
httpClient: new ImpitHttpClient(),
|
|
773
|
+
sessionPool: new SessionPool({
|
|
774
|
+
createSessionFunction: async (opts) =>
|
|
775
|
+
new Session({
|
|
776
|
+
...opts?.sessionOptions,
|
|
777
|
+
fingerprint: { browser: 'firefox', platform: 'linux', device: 'desktop' },
|
|
778
|
+
}),
|
|
779
|
+
}),
|
|
780
|
+
});
|
|
781
|
+
```
|
|
782
|
+
|
|
783
|
+
See the [Avoid getting blocked](https://crawlee.dev/js/docs/guides/avoid-blocking) guide for how the session fingerprint interacts with both HTTP and browser crawlers.
|
|
784
|
+
|
|
785
|
+
### `HttpClient` instances return `Response` objects
|
|
786
|
+
|
|
787
|
+
The interface of `HttpClient` instances was changed to return the [native `Response` objects](https://developer.mozilla.org/en-US/docs/Web/API/Response) instead of custom `HttpResponse` objects.
|
|
788
|
+
|
|
789
|
+
### `CrawlingContext.response` is now of type `Response`
|
|
790
|
+
|
|
791
|
+
The `CrawlingContext.response` property is now of type [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) instead of `HttpResponse`. `CrawlingContext.sendRequest` method now returns `Response` objects as well.
|
|
792
|
+
|
|
793
|
+
### Multiple crawler instances use separate default request queues
|
|
794
|
+
|
|
795
|
+
In v3, every `BasicCrawler` (or subclass) that didn't receive an explicit `requestQueue` option would open the same default request queue. If you created two crawlers in the same process, they would silently share a queue — leading to request collisions and hard-to-debug deduplication issues.
|
|
796
|
+
|
|
797
|
+
In v4, only the **first** crawler instance uses the default request queue. Each subsequent instance automatically gets its own queue via an internal alias (e.g. `__default_1__`, `__default_2__`, etc.). This means multiple crawlers can safely coexist without interfering with each other's requests.
|
|
798
|
+
|
|
799
|
+
If you explicitly pass a `requestQueue` (or `requestManager`) to the crawler, that queue is used as-is regardless of instance order.
|
|
800
|
+
|
|
801
|
+
### Repeated `run()` calls no longer empty the request queue
|
|
802
|
+
|
|
803
|
+
In v3, calling `crawler.run()` again on the same instance dropped the default request queue and created a fresh one, so the same URLs were crawled again — but only for a queue actually named `default`, which the Apify platform's default queue is not, so on the platform the second run silently crawled nothing.
|
|
804
|
+
|
|
805
|
+
v4 does the same thing everywhere: nothing is emptied between runs. A repeated `run()` continues with the same request manager, and requests the previous run handled — a failed request counts as handled — are not processed again. Any crawl that ends up processing nothing while its request manager holds only handled requests warns and says why, instead of finishing silently; that also covers a second crawler sharing the queue, or a queue a previous process already worked through.
|
|
806
|
+
|
|
807
|
+
The `purgeRequestQueue` option of `crawler.run()` went away with the automatic purge. To crawl the same requests again, empty the queue yourself:
|
|
808
|
+
|
|
809
|
+
```typescript
|
|
810
|
+
const crawler = new BasicCrawler({ requestHandler: async ({ request }) => { /* ... */ } });
|
|
811
|
+
await crawler.run(['https://example.com/a', 'https://example.com/b']);
|
|
812
|
+
|
|
813
|
+
const requestManager = await crawler.getRequestManager();
|
|
814
|
+
await requestManager.purge?.();
|
|
815
|
+
|
|
816
|
+
// The same URLs are crawled again:
|
|
817
|
+
await crawler.run(['https://example.com/a', 'https://example.com/c']);
|
|
818
|
+
```
|
|
819
|
+
|
|
820
|
+
`purge()` — empty the storage, keep its id and name — is new in v4 and available on `Dataset`, `KeyValueStore` and `RequestQueue`, as well as being an optional method on the `IRequestManager` interface. The Apify platform is the exception. Its API has no in-place empty, so all three throw there. The error points you at `drop()` or a fresh storage.
|
|
821
|
+
|
|
822
|
+
This has nothing to do with `purgeOnStart` / `CRAWLEE_PURGE_ON_START`, which still wipes the default storages once per process before the first run.
|
|
823
|
+
|
|
824
|
+
Most of the time you can avoid the purge entirely. Every crawler instance opens a request queue of its own (see the section above). A crawler per crawl therefore needs neither a purge nor any queue wiring. Pass `RequestQueue.open({ alias })` when you do want to hold on to that queue:
|
|
825
|
+
|
|
826
|
+
```typescript
|
|
827
|
+
for (const [index, urls] of batches.entries()) {
|
|
828
|
+
const crawler = new BasicCrawler({
|
|
829
|
+
// Optional — a fresh crawler gets its own queue anyway. Pass one to decide which.
|
|
830
|
+
requestManager: await RequestQueue.open({ alias: `batch-${index}` }),
|
|
831
|
+
requestHandler: async ({ request }) => { /* ... */ },
|
|
832
|
+
});
|
|
833
|
+
|
|
834
|
+
await crawler.run(urls);
|
|
835
|
+
}
|
|
836
|
+
```
|
|
837
|
+
|
|
838
|
+
An alias identifies a run-scoped queue. It has no persistent name, and is emptied on start along with the default storages. Reuse an alias and you get that same queue back, handled requests included. The next crawl then finds nothing to do. Give each crawl its own alias. `purge()` is for when one crawler and one queue must be reused.
|
|
839
|
+
|
|
840
|
+
### `teardown()` is per-run, disposing of the crawler is not
|
|
841
|
+
|
|
842
|
+
`crawler.teardown()` ends the run in progress and releases only what that run owns — it is what `run()` calls on its way out. In v3 it also destroyed the browser pool a browser crawler had built for itself, and a destroyed `BrowserPool` cannot be used again: with its timers cleared and its listeners dropped, a second `run()` had nothing retiring idle browsers or reaping the retired ones. It now releases that run's browsers and leaves the pool usable.
|
|
843
|
+
|
|
844
|
+
What outlives a run is released by `crawler.destroy()`, or by disposing of the crawler:
|
|
845
|
+
|
|
846
|
+
```typescript
|
|
847
|
+
{
|
|
848
|
+
await using crawler = new PlaywrightCrawler({ requestHandler: async ({ page }) => { /* ... */ } });
|
|
849
|
+
|
|
850
|
+
await crawler.run(['https://example.com/a']);
|
|
851
|
+
await crawler.run(['https://example.com/b']);
|
|
852
|
+
} // the browser pool is destroyed here, as the crawler goes out of scope
|
|
853
|
+
```
|
|
854
|
+
|
|
855
|
+
Disposing is optional — a finished run leaves no browsers open and no timer holding the process alive.
|
|
856
|
+
|
|
857
|
+
:::info
|
|
858
|
+
|
|
859
|
+
The `await using` syntax needs Node.js 24 or later. On Node.js 22 call `destroy()` yourself instead — it is what the disposal hook calls anyway, as with the [collaborators you own](#collaborators-you-own-are-disposable).
|
|
860
|
+
|
|
861
|
+
:::
|
|
862
|
+
|
|
863
|
+
`crawler.running` is now a read-only getter; in v3 it was an assignable field.
|
|
864
|
+
|
|
865
|
+
### Storage `.open()` now also accepts `{ id?, name? }`
|
|
866
|
+
|
|
867
|
+
`Dataset.open()`, `KeyValueStore.open()`, and `RequestQueue.open()` previously accepted a single `idOrName?: string` parameter. This was ambiguous — callers couldn't express whether they were opening a storage by its ID or by name.
|
|
868
|
+
|
|
869
|
+
The first parameter now also accepts a `StorageIdentifier` object with separate `id`, `name` and `alias` fields (at most one of them):
|
|
870
|
+
|
|
871
|
+
```typescript
|
|
872
|
+
interface StorageIdentifier {
|
|
873
|
+
id?: string;
|
|
874
|
+
name?: string;
|
|
875
|
+
alias?: string; // run-scoped, purged on start; see the request queue section
|
|
876
|
+
}
|
|
877
|
+
```
|
|
878
|
+
|
|
879
|
+
Passing a plain string still works — it is first looked up as an ID, and if no such storage exists, it is treated as a name (matching the v3 behavior):
|
|
880
|
+
|
|
881
|
+
```typescript
|
|
882
|
+
const dataset = await Dataset.open('my-dataset');
|
|
883
|
+
const store = await KeyValueStore.open('my-store');
|
|
884
|
+
const queue = await RequestQueue.open('my-queue');
|
|
885
|
+
```
|
|
886
|
+
|
|
887
|
+
You can also use the object form, which additionally allows opening a storage by ID:
|
|
888
|
+
|
|
889
|
+
```typescript
|
|
890
|
+
const dataset = await Dataset.open({ name: 'my-dataset' });
|
|
891
|
+
|
|
892
|
+
// Opening by ID (e.g. on the Apify platform):
|
|
893
|
+
const datasetById = await Dataset.open({ id: 'WkzbQMuFYuamGv3YF' });
|
|
894
|
+
```
|
|
895
|
+
|
|
896
|
+
Opening the default storage (no arguments or `null`) still works as before:
|
|
897
|
+
|
|
898
|
+
```typescript
|
|
899
|
+
const dataset = await Dataset.open();
|
|
900
|
+
```
|
|
901
|
+
|
|
902
|
+
The same change applies to `CrawlingContext.getKeyValueStore()` and `CrawlingContext.pushData()` — both now accept `string | StorageIdentifier` for identifying the target storage.
|
|
903
|
+
|
|
904
|
+
### Storage writes in request handlers are transactional
|
|
905
|
+
|
|
906
|
+
Every crawler now wraps each request in a **storage transaction** (see the [Transactional storage](https://crawlee.dev/js/docs/next/guides/result-storage#transactional-storage) section of the Result Storage guide): storage writes made anywhere in the request lifecycle — hooks, `extendContext` and the request handler alike — are recorded and only applied to real storage when the request handler succeeds. A handler that throws leaves no partial writes behind, and a retry does not duplicate data.
|
|
907
|
+
|
|
908
|
+
The observable behavior of a *successful* handler is unchanged (reads within a handler see its own writes), but several things differ on the failure path and around handler boundaries:
|
|
909
|
+
|
|
910
|
+
- **Uncommitted writes are invisible to other handlers.** Using the key-value store as a live channel between concurrently running handlers no longer works — one handler's `setValue()` only becomes visible to others once its request succeeds. Use `useState()` for cross-handler communication.
|
|
911
|
+
- **`useState()` / `getAutoSavedValue()` are *not* transactional.** The shared state object stays live; mutations of it are not rolled back when a handler fails. Side effects that have to match the writes that actually landed — result counters above all — belong in a callback registered with the new `afterStorageCommit()` context helper.
|
|
912
|
+
- **Request queue additions are applied immediately by default** (the `writeThrough` policy) and are not rolled back — deduplication by `uniqueKey` keeps retries idempotent. Pass `transactionalStorage: { requestQueue: 'deferred' }` for strict all-or-nothing enqueues.
|
|
913
|
+
- **Commit is at-least-once.** It spans multiple storages, so a commit that fails partway fails the request; the retry may re-apply writes that already landed.
|
|
914
|
+
- **A write cannot fail where it is made.** `pushData()` records the item and returns; if the storage backend rejects it, that happens at commit time, and a `try`/`catch` around the call never sees it. Register an `afterStorageCommit()` callback next to the write instead — it receives the commit error, and an error it throws replaces it, so a rejected write can still be turned into a `NonRetryableError` of your own.
|
|
915
|
+
- **`KeyValueStore.setValue()` with a stream value throws inside a request handler.** A stream can only be consumed once, so it cannot be buffered. Wrap the call in `withDirectStorageAccess()` to write it immediately:
|
|
916
|
+
|
|
917
|
+
```typescript
|
|
918
|
+
import { withDirectStorageAccess } from 'crawlee';
|
|
919
|
+
|
|
920
|
+
await withDirectStorageAccess(async () => keyValueStore.setValue('video', stream, { contentType: 'video/mp4' }));
|
|
921
|
+
```
|
|
922
|
+
|
|
923
|
+
- **`drop()`, `purge()` and the request queue processing internals throw inside a request handler**, since no rollback could undo them. `withDirectStorageAccess()` is the escape hatch there, too.
|
|
924
|
+
- **Key listing order changes inside a handler**: `keys()`, `values()` and `entries()` emit the handler's own (buffered) keys first, then the rest.
|
|
925
|
+
|
|
926
|
+
The mechanism can be disabled entirely with `transactionalStorage: false` on any crawler except `AdaptivePlaywrightCrawler` (which needs it to discard the writes of its losing request handler attempts).
|
|
927
|
+
|
|
928
|
+
#### Removed symbols and options
|
|
929
|
+
|
|
930
|
+
- `checkStorageAccess` and `withCheckedStorageAccess` are superseded by the transaction mechanism; the per-call-site helper is now `withDirectStorageAccess()`.
|
|
931
|
+
- The experimental `AdaptivePlaywrightCrawler` no longer needs its bespoke write-buffering machinery: the `preventDirectStorageAccess` option is gone (direct storage calls are now captured by the per-attempt transaction instead of throwing), and `RequestHandlerResult` is replaced by the read-only `StorageTransactionView`, which the `resultChecker` / `resultComparator` callbacks (and `fullResultComparator`) now receive. The view keeps the familiar accessors (`datasetItems`, `enqueuedUrls`, `keyValueStoreChanges`), so most callbacks only need a type change. The `calls` and `enqueuedUrlLists` accessors are gone — `requestsFromUrl` sources are now expanded when added, so the fetched URLs appear in `enqueuedUrls` (and are what `fullResultComparator` compares). The `commitResult` override point is gone too; use an `afterStorageCommit()` callback to run logic once the winning attempt's writes have landed (or failed to).
|
|
932
|
+
|
|
933
|
+
### `storageObject` is removed from storage classes
|
|
934
|
+
|
|
935
|
+
The `storageObject` property (the raw backend record exposed on `Dataset`, `KeyValueStore` and `RequestQueue` instances) is removed. The commonly used fields are available directly on the instance as `id` and `name`, and `Dataset.getInfo()` returns the full metadata:
|
|
936
|
+
|
|
937
|
+
```ts
|
|
938
|
+
// v3
|
|
939
|
+
const { id, name } = dataset.storageObject;
|
|
940
|
+
|
|
941
|
+
// v4
|
|
942
|
+
const { id, name } = dataset;
|
|
943
|
+
const info = await dataset.getInfo();
|
|
944
|
+
```
|
|
945
|
+
|
|
946
|
+
### `KeyValueStore.getPublicUrl` is now async
|
|
947
|
+
|
|
948
|
+
The `KeyValueStore.getPublicUrl` method is now asynchronous and reads the public URL directly from the storage backend.
|
|
949
|
+
|
|
950
|
+
### `MemoryStorage` split into `FileSystemStorageBackend` and `MemoryStorageBackend`
|
|
951
|
+
|
|
952
|
+
In v3, the single `MemoryStorage` class from `@crawlee/memory-storage` did double duty: it kept everything in memory *and*, by default, mirrored it to disk (toggled via the `persistStorage` option / `CRAWLEE_PERSIST_STORAGE` environment variable). In v4 these two responsibilities are split into two independent classes, and the default storage backend now persists to disk.
|
|
953
|
+
|
|
954
|
+
- **`FileSystemStorageBackend`** (new, in the new `@crawlee/fs-storage` package) — always persists storage to the local directory (`CRAWLEE_STORAGE_DIR`, default `./storage`). This is what you get implicitly when you don't configure a storage backend, and it is the behavior the old `MemoryStorage` had with its default `persistStorage: true`.
|
|
955
|
+
- **`MemoryStorageBackend`** (the renamed `MemoryStorage`, now part of `@crawlee/core`) — keeps everything purely in memory and **never touches the disk**. This matches the old `MemoryStorage` with `persistStorage: false`. The standalone `@crawlee/memory-storage` package no longer exists; its code was merged into `@crawlee/core`.
|
|
956
|
+
|
|
957
|
+
Both classes are re-exported from the `crawlee` meta-package.
|
|
958
|
+
|
|
959
|
+
#### The default storage backend now persists to disk
|
|
960
|
+
|
|
961
|
+
Which client backs the implicit default is decided by `Configuration.persistStorage` (still controllable via the `CRAWLEE_PERSIST_STORAGE` environment variable): `true` (the default) selects `FileSystemStorageBackend`, `false` selects `MemoryStorageBackend`. If you relied on the default and never set `persistStorage`, your storage is persisted to disk exactly as before — no change.
|
|
962
|
+
|
|
963
|
+
#### `MemoryStorage` is renamed and is now memory-only
|
|
964
|
+
|
|
965
|
+
If you constructed the storage backend explicitly, two things changed:
|
|
966
|
+
|
|
967
|
+
1. **The class is renamed** `MemoryStorage` → `MemoryStorageBackend`.
|
|
968
|
+
2. **It no longer writes to disk.** A bare `new MemoryStorage()` in v3 persisted to disk by default; `new MemoryStorageBackend()` in v4 does not. If you want persistence, use `FileSystemStorageBackend` instead.
|
|
969
|
+
|
|
970
|
+
**Before:**
|
|
971
|
+
```typescript
|
|
972
|
+
import { MemoryStorage } from '@crawlee/memory-storage';
|
|
973
|
+
|
|
974
|
+
// Persisted to disk by default in v3.
|
|
975
|
+
const storageBackend = new MemoryStorage();
|
|
976
|
+
```
|
|
977
|
+
|
|
978
|
+
**After:**
|
|
979
|
+
```typescript
|
|
980
|
+
import { FileSystemStorageBackend } from '@crawlee/fs-storage';
|
|
981
|
+
import { MemoryStorageBackend } from '@crawlee/core';
|
|
982
|
+
|
|
983
|
+
// Persists to disk (the old default behavior):
|
|
984
|
+
const storageBackend = new FileSystemStorageBackend({ localDataDirectory: './storage' });
|
|
985
|
+
|
|
986
|
+
// Or keep everything in memory only (the old `persistStorage: false`):
|
|
987
|
+
const inMemory = new MemoryStorageBackend();
|
|
988
|
+
```
|
|
989
|
+
|
|
990
|
+
`MemoryStorageBackend` no longer takes the `localDataDirectory`, `persistStorage`, or `writeMetadata` options — in-memory storage has nowhere to write, so they had no meaning. `FileSystemStorageBackend` requires `localDataDirectory` (constructed explicitly, it does not fall back to `CRAWLEE_STORAGE_DIR`); it always persists, so it has no `persistStorage` option, and the `writeMetadata` option has been removed there too (see [`writeMetadata` option removed](#writemetadata-option-removed)).
|
|
991
|
+
|
|
992
|
+
#### No request lock expiry in `MemoryStorageBackend`
|
|
993
|
+
|
|
994
|
+
Because the in-memory queue lives entirely within a single process and is never shared with another consumer, `MemoryStorageBackend`'s request queue no longer uses an expiring, cross-process lock. A fetched request simply stays *in progress* until it is handled or reclaimed; it never becomes fetchable again on its own after a timeout. `setExpectedRequestProcessingTime()` is therefore a no-op for in-memory storage. (Disk-backed `FileSystemStorageBackend` keeps the lock-with-expiry behavior.)
|
|
995
|
+
|
|
996
|
+
#### `writeMetadata` option removed
|
|
997
|
+
|
|
998
|
+
`FileSystemStorageBackend` no longer accepts the `writeMetadata` option. The underlying file-system storage now always writes metadata files (`__metadata__.json` for each storage and a `<key>.__metadata__.json` sidecar for each key-value record), so the toggle no longer had any effect. Remove it from your storage backend options:
|
|
999
|
+
|
|
1000
|
+
```diff
|
|
1001
|
+
import { FileSystemStorageBackend } from '@crawlee/fs-storage';
|
|
1002
|
+
|
|
1003
|
+
const storageBackend = new FileSystemStorageBackend({
|
|
1004
|
+
localDataDirectory: './storage',
|
|
1005
|
+
- writeMetadata: true,
|
|
1006
|
+
});
|
|
1007
|
+
```
|
|
1008
|
+
|
|
1009
|
+
`MemoryStorageBackend` never accepted `writeMetadata` (it has no on-disk format to begin with), so there is nothing to change there.
|
|
1010
|
+
|
|
1011
|
+
### Out-of-band key-value files (e.g. a hand-placed `INPUT.json`)
|
|
1012
|
+
|
|
1013
|
+
Keys are literal. `aaa` and `aaa.json` are two distinct keys, and `FileSystemStorageBackend` never infers a key from a file's extension — in v3 a hand-placed `aaa.json` was readable as `aaa`, in v4 it is not.
|
|
1014
|
+
|
|
1015
|
+
What v4 does instead is *adopt* value files that turn up in a store directory without the `<key>.__metadata__.json` sidecar that marks a record — the Apify CLI's input, a project template, a v3 store directory, a file you dropped in with an editor. Opening the store writes the missing sidecar (the value bytes are never touched), and from then on the file is an ordinary record: read by `getValue`, enumerated by `listKeys`, removed by `deleteValue`. Two rules decide the key:
|
|
1016
|
+
|
|
1017
|
+
- A subclass of `FileSystemStorageBackend` may claim specific files under a key of its own by overriding `keyValueStoreAdoptionCandidates`. The Apify SDK's `ApifyFileSystemStorageBackend` claims a bare `INPUT` or `INPUT.json` in the **default** store (and the same for the configured `ACTOR_INPUT_KEY`) as the record `INPUT`: the file keeps its name, `listKeys` reports `INPUT`, `getValue('INPUT.json')` is `null`, and `getPublicUrl('INPUT')` points at `INPUT.json`. If both files are present, opening the store fails instead of guessing which one is the input. Plain Crawlee claims nothing, so there a bare `INPUT.json` is just a file named `INPUT.json`.
|
|
1018
|
+
- Every other sidecar-less file becomes a record **keyed by its filename**, in every store: a hand-placed `some-key.json` is the key `some-key.json`, and so is an `INPUT.json` in a store other than the default one. Dotfiles are skipped.
|
|
1019
|
+
|
|
1020
|
+
A `.json` file is adopted as `application/json; charset=utf-8` and anything else as `application/octet-stream`; there is no content sniffing. Adopted records are subject to the purge of the default store on start like any other record, unless a subclass spares them through `purgeKeyValueStore` — the Apify SDK keeps its run input this way.
|
|
1021
|
+
|
|
1022
|
+
Beyond the literal keys, three v3 behaviors are gone:
|
|
1023
|
+
|
|
1024
|
+
- **`INPUT.txt` and `INPUT.bin` are no longer the input.** v3 probed those extensions too. In v4 they are adopted under their own names, so `getValue('INPUT')` returns `null` and the purge on start deletes them. Rename such an input to `INPUT.json` (or drop the extension) before upgrading.
|
|
1025
|
+
- **Extensionless input files report `application/octet-stream`.** In v3 a bare value file with no extension was read as `text/plain`. Give the file a `.json` extension if you need a more specific type.
|
|
1026
|
+
- **Malformed input files are no longer silently swallowed.** In v3 an `INPUT.json` containing invalid JSON was treated as a missing record (`getValue` returned `null`). In v4 the raw bytes are returned verbatim and parsing happens in the `KeyValueStore` frontend, so a malformed value surfaces a parse error at read time instead of looking absent.
|
|
1027
|
+
|
|
1028
|
+
### `globs`, `regexps`, and `pseudoUrls` replaced by `include`
|
|
1029
|
+
|
|
1030
|
+
The separate `globs`, `regexps`, and `pseudoUrls` URL-filtering options of `enqueueLinks()`, the click-elements enqueue helpers, and `SitemapRequestLoader` have been collapsed into a single `include` option (mirroring the already-unified `exclude` option).
|
|
1031
|
+
|
|
1032
|
+
The `PseudoUrl` class is no longer exported and the `@apify/pseudo_url` dependency has been dropped. Rewrite any pseudo-URL patterns as globs or regular expressions.
|
|
1033
|
+
|
|
1034
|
+
Per-pattern request options (`label`, `userData`, `method`, `payload`, `headers` set directly on a pattern object) are no longer supported. Use the top-level `label` / `userData` options, or `transformRequestFunction`, to set request options for the enqueued requests.
|
|
1035
|
+
|
|
1036
|
+
**Before:**
|
|
1037
|
+
```typescript
|
|
1038
|
+
await enqueueLinks({
|
|
1039
|
+
globs: ['https://crawlee.dev/docs/**'],
|
|
1040
|
+
regexps: [/\/blog\//],
|
|
1041
|
+
});
|
|
1042
|
+
```
|
|
1043
|
+
|
|
1044
|
+
**After:**
|
|
1045
|
+
```typescript
|
|
1046
|
+
await enqueueLinks({
|
|
1047
|
+
include: ['https://crawlee.dev/docs/**', /\/blog\//],
|
|
1048
|
+
});
|
|
1049
|
+
```
|
|
1050
|
+
|
|
1051
|
+
#### Migrating `pseudoUrls`
|
|
1052
|
+
|
|
1053
|
+
A `PseudoUrl` is equivalent to an anchored, case-insensitive regular expression: the text inside `[ ]` is the pattern (a wildcard), everything outside it is matched literally, and the whole URL is anchored. Translate each pseudo-URL to a `RegExp` (or a glob, if the pattern is simple enough):
|
|
1054
|
+
|
|
1055
|
+
**Before:**
|
|
1056
|
+
```typescript
|
|
1057
|
+
await enqueueLinks({
|
|
1058
|
+
pseudoUrls: ['https://crawlee.dev/[.*]'],
|
|
1059
|
+
});
|
|
1060
|
+
```
|
|
1061
|
+
|
|
1062
|
+
**After:**
|
|
1063
|
+
```typescript
|
|
1064
|
+
await enqueueLinks({
|
|
1065
|
+
// faithful translation — [.*] becomes .*, literal text is escaped and anchored, matching ignores case
|
|
1066
|
+
include: [/^https:\/\/crawlee\.dev\/.*$/i],
|
|
1067
|
+
// or, when the pattern is simple, an equivalent glob:
|
|
1068
|
+
// include: ['https://crawlee.dev/**'],
|
|
1069
|
+
});
|
|
1070
|
+
```
|
|
1071
|
+
|
|
1072
|
+
#### `include` patterns no longer replace the enqueue strategy
|
|
1073
|
+
|
|
1074
|
+
In v3, providing any URL patterns (`globs`, `regexps`, `pseudoUrls`) disabled the default enqueue strategy - the patterns were the only filter. In v4, the `strategy` **always applies** and is combined with `include` using AND logic: a URL must match an `include` pattern *and* satisfy the strategy (default `same-hostname`) to be enqueued. This mirrors the behavior of Crawlee for Python.
|
|
1075
|
+
|
|
1076
|
+
The practical consequence: patterns that used to match URLs on other hostnames (e.g. subdomains) now silently enqueue nothing unless you relax the strategy explicitly:
|
|
1077
|
+
|
|
1078
|
+
```ts
|
|
1079
|
+
// v3 - the glob alone allowed subdomains
|
|
1080
|
+
await enqueueLinks({
|
|
1081
|
+
globs: ['https://*.example.com/'],
|
|
1082
|
+
});
|
|
1083
|
+
|
|
1084
|
+
// v4 - the default same-hostname strategy would filter the subdomains out again,
|
|
1085
|
+
// so relax it explicitly
|
|
1086
|
+
await enqueueLinks({
|
|
1087
|
+
include: ['https://*.example.com/'],
|
|
1088
|
+
strategy: 'same-domain',
|
|
1089
|
+
});
|
|
1090
|
+
```
|
|
1091
|
+
|
|
1092
|
+
### Enqueue strategies ignore the port, except `same-origin`
|
|
1093
|
+
|
|
1094
|
+
In `enqueueLinks`, `same-hostname` and `same-domain` now compare hostnames only, so `http://example.com:8080/a` matches a base URL of `https://example.com/`. In v3, `enqueueLinks` required the port to match. `same-origin` still requires the same scheme, hostname and port. Hosts without a registrable domain (IP addresses, `localhost`) are matched by `same-domain` like `same-hostname`. Sitemap and robots.txt filtering and the post-redirect strategy check follow the same rules.
|
|
1095
|
+
|
|
1096
|
+
### `transformRequestFunction` precedence in `enqueueLinks`
|
|
1097
|
+
|
|
1098
|
+
The `transformRequestFunction` callback in `enqueueLinks` now runs **after** URL pattern filtering (`include`, `exclude`) instead of before. This means it has the highest priority and can overwrite any request options set by the global `label` / `userData` options.
|
|
1099
|
+
|
|
1100
|
+
The priority order is now (lowest to highest):
|
|
1101
|
+
1. Global `label` / `userData` options
|
|
1102
|
+
2. `transformRequestFunction`
|
|
1103
|
+
|
|
1104
|
+
The `transformRequestFunction` callback receives a `RequestOptions` object and can return either:
|
|
1105
|
+
- The modified `RequestOptions` object
|
|
1106
|
+
- A new `RequestOptions` plain object
|
|
1107
|
+
- `'unchanged'` to keep the original options as-is
|
|
1108
|
+
- A falsy value or `'skip'` to exclude the request from the queue
|
|
1109
|
+
|
|
1110
|
+
### `enqueueLinks()` return value reshaped: `AddRequestsBatchedResult` instead of `BatchAddRequestsResult`
|
|
1111
|
+
|
|
1112
|
+
`enqueueLinks()` (and `context.addRequests()`) now return the same `AddRequestsBatchedResult` object that `crawler.addRequests()` / `queue.addRequestsBatched()` already returned in v3, instead of repackaging it into the legacy `BatchAddRequestsResult` shape:
|
|
1113
|
+
|
|
1114
|
+
| Before (`BatchAddRequestsResult`) | After (`AddRequestsBatchedResult`) |
|
|
1115
|
+
| --- | --- |
|
|
1116
|
+
| `processedRequests` | `addedRequests` |
|
|
1117
|
+
| `unprocessedRequests` (always `[]` — `enqueueLinks()` never actually populated it) | *(removed — rejected requests are warned about and skipped, see [`RequestQueue.addRequestsBatched` no longer retries rejected requests](./request-loaders.md#requestqueueaddrequestsbatched-no-longer-retries-rejected-requests))* |
|
|
1118
|
+
| *(not exposed)* | `waitForAllRequestsToBeAdded` — a promise resolving with the requests added in batches after the first (new) |
|
|
1119
|
+
| *(not exposed)* | `requestsOverLimit` — requests dropped because of the `limit` / `maxRequestsPerCrawl` budget (new) |
|
|
1120
|
+
|
|
1121
|
+
**Before:**
|
|
1122
|
+
```typescript
|
|
1123
|
+
const { processedRequests } = await enqueueLinks();
|
|
1124
|
+
```
|
|
1125
|
+
|
|
1126
|
+
**After:**
|
|
1127
|
+
```typescript
|
|
1128
|
+
const { addedRequests } = await enqueueLinks();
|
|
1129
|
+
```
|
|
1130
|
+
|
|
1131
|
+
### `extractLinks()`: extracting URLs without enqueueing them
|
|
1132
|
+
|
|
1133
|
+
Crawling contexts that support `enqueueLinks()` (Cheerio, JSDOM, LinkeDOM, and browser-based crawlers) now also expose an `extractLinks()` helper that returns the matching URLs as strings, without adding them to the request queue:
|
|
1134
|
+
|
|
1135
|
+
```typescript
|
|
1136
|
+
const urls = await extractLinks({ selector: '.product-link' });
|
|
1137
|
+
```
|
|
1138
|
+
|
|
1139
|
+
`enqueueLinks()` itself is unchanged in behavior — it now calls `extractLinks()` internally and forwards the URLs to `context.addRequests()`.
|
|
1140
|
+
|
|
1141
|
+
### `context.addRequests()` now applies `enqueueLinks`-style filtering, and `BasicCrawler` no longer has `enqueueLinks`
|
|
1142
|
+
|
|
1143
|
+
`context.addRequests()` (and `crawler.addRequests()`) accept the same `include` / `exclude` / `strategy` / `transformRequestFunction` / `onSkippedRequest` options as `enqueueLinks()`, and resolve `baseUrl`-relative URLs the same way. Unlike `enqueueLinks()`, there is no implicit "current page" to anchor the strategy to, so `strategy` defaults to `EnqueueStrategy.All` here instead of `EnqueueStrategy.SameHostname`.
|
|
1144
|
+
|
|
1145
|
+
`context.addRequests()` also now returns an `AddRequestsBatchedResult` (previously it resolved to `void`).
|
|
1146
|
+
|
|
1147
|
+
`BasicCrawler` (and its `BasicCrawlingContext`) no longer has an `enqueueLinks()` method — `BasicCrawler` has no concept of a page to extract links from. `enqueueLinks()` remains available on crawlers with web content (`CheerioCrawler` and the other DOM crawlers, `PlaywrightCrawler`, `PuppeteerCrawler`, etc.; plain `HttpCrawler` has none), now implemented in terms of `extractLinks()` + `addRequests()`.
|
|
1148
|
+
|
|
1149
|
+
The `robotsTxtFile` / `respectRobotsTxtFile` per-call options are removed from `enqueueLinks()` — robots.txt filtering is applied by the crawler consistently via `BasicCrawlerOptions.respectRobotsTxtFile`.
|
|
1150
|
+
|
|
1151
|
+
### `onSkippedRequest` receives a `Request` instead of a URL string
|
|
1152
|
+
|
|
1153
|
+
The callback now gets `{ request, reason }` instead of `{ url, reason }` — use `request.url` for the URL.
|
|
1154
|
+
|
|
1155
|
+
### Skipping a request with `context.skipRequest()`
|
|
1156
|
+
|
|
1157
|
+
In v3, skipping a request without it counting as a failure took a hack: set `request.noRetry`, throw, then decrement `requestsFailed` and silence the error log. Call `skipRequest(message?)` from the crawling context instead — in `extendContext`, a navigation hook, the request handler or the `errorHandler`. The request is marked as handled with `state` set to `RequestState.SKIPPED`, is neither retried nor passed to `failedRequestHandler`, and `onSkippedRequest` fires with the new `'manual'` reason. Storage writes made for the request before the skip are rolled back.
|
|
1158
|
+
|
|
1159
|
+
See the [Skipping requests](https://crawlee.dev/js/docs/next/examples/skip-request) example.
|
|
1160
|
+
|
|
1161
|
+
### robots.txt error responses follow RFC 9309
|
|
1162
|
+
|
|
1163
|
+
v3 parsed the body of a robots.txt response regardless of its status code. v4 follows [RFC 9309](https://www.rfc-editor.org/rfc/rfc9309#section-2.3.1.3) instead: a `4xx` response allows everything and a `5xx` response disallows everything, whatever the body says.
|
|
1164
|
+
|
|
1165
|
+
With `respectRobotsTxtFile` enabled, a site that answers `/robots.txt` with a `5xx` is therefore skipped entirely. The crawler caches robots.txt per origin for the whole run, so every request to that origin is skipped with the `robotsTxt` reason.
|
|
1166
|
+
|
|
1167
|
+
### `sameDomainDelaySecs` is now backed by `ThrottlingRequestManager`
|
|
1168
|
+
|
|
1169
|
+
`sameDomainDelaySecs` still works and still means what it did in v3 — subdomains included, it paces a whole registrable domain rather than a single host. Underneath, it is now a floor reported to the crawler's request manager as a [pacing signal](./request-loaders.md#irequestmanager-gained-recordpacingsignal); only when nothing there paces does the crawler wrap its manager in a `ThrottlingRequestManager`, which gives each domain a queue of its own so a delayed request waits in storage rather than in an in-memory map. Consequences worth knowing about:
|
|
1170
|
+
|
|
1171
|
+
- A crawl that discovers more than `maxThrottledDomains` domains (100 by default) throws instead of quietly running out of steam. Pass your own `ThrottlingRequestManager` as `requestManager` to raise the ceiling — or crawl fewer sites.
|
|
1172
|
+
- Combined with a manager that paces on its own, a `ThrottlingRequestManager` with `domains: 'all'` and `throttleBy: 'registrableDomain'` takes the delay as its `minCrawlDelaySecs` floor, wherever it sits in a composition. One that paces only *some* domains, or keeps the default `throttleBy: 'hostname'`, throws instead — set `domains: 'all'` and `throttleBy: 'registrableDomain'`, or configure the delay there yourself and drop the option.
|
|
1173
|
+
- Requests that never pass through the request manager — those from a `requestsFromUrl` list — are not paced, and the crawler warns when it hands one out.
|
|
1174
|
+
|
|
1175
|
+
### Internal KVS keys renamed
|
|
1176
|
+
|
|
1177
|
+
Several internal Crawlee keys were prefixed with the `SDK_` prefix for legacy reasons — these keys now start with `CRAWLEE_` instead. These are, e.g., `CRAWLEE_SESSION_POOL_STATE_{id}` (the pool id is now appended) or `CRAWLEE_CRAWLER_STATISTICS_{n}`.
|
|
1178
|
+
|
|
1179
|
+
## Only if you subclassed crawlers or touched internals
|
|
1180
|
+
|
|
1181
|
+
Skip this section unless you subclass Crawlee classes, override `protected` members, or read fields that were never documented. Many protected methods lost their underscore prefix, private members became native `#` fields, and a long list of accidentally exposed members is now `private` or `@internal`. Crawler generics, handler types and navigation hook types were reshaped, `Request` was split into `Request` and `CrawlingRequest`, and `RecoverableState` changed its serialization contract.
|
|
1182
|
+
|
|
1183
|
+
See [Upgrading to v4: subclassing and internals](./internals.md) for the details.
|
|
1184
|
+
|
|
1185
|
+
## Only if you manage sessions or proxies yourself
|
|
1186
|
+
|
|
1187
|
+
Applies when you construct `SessionPool` or `Session` instances directly, implement your own pool, or configure proxies beyond a static URL list. Crawlers accept any `ISessionPool` implementation, `createSessionFunction` no longer receives the pool, and `Session` no longer references its pool or emits `sessionRetired`. `tieredProxyUrls` is gone in favor of named sessions, and `ProxyConfiguration.newUrl()` / `newProxyInfo()` dropped their `sessionId` argument.
|
|
1188
|
+
|
|
1189
|
+
See [Upgrading to v4: sessions and proxies](./sessions-and-proxies.md) for the details.
|
|
1190
|
+
|
|
1191
|
+
## Only if you customize browser management
|
|
1192
|
+
|
|
1193
|
+
Applies when you construct a `BrowserPool` yourself, reach for `browserController`, or tune `AdaptivePlaywrightCrawler` internals. Crawlers accept any `IBrowserPool`, `@crawlee/browser-pool` is no longer re-exported from `crawlee`, and `browserController` is gone from the crawling context. Puppeteer cookies are synced at the browser-context level, a rendering type predictor you pass in is yours to initialize, and several unused options, types and `BrowserPool` internals were removed.
|
|
1194
|
+
|
|
1195
|
+
See [Upgrading to v4: browser management](./browser-management.md) for the details.
|
|
1196
|
+
|
|
1197
|
+
## Only if you customize crawler statistics
|
|
1198
|
+
|
|
1199
|
+
Applies when you passed `statisticsOptions` to a crawler, subclassed `Statistics`, or passed type arguments to `BrowserCrawler`/`BrowserCrawlerOptions`. `statisticsOptions` is replaced by passing a `Statistics` (or any `IStatistics`) instance, the `*Job()` recording methods are renamed, persistence is stricter, and extra persisted fields are declared with the `stateExtension` option instead of subclassing.
|
|
1200
|
+
|
|
1201
|
+
See [Upgrading to v4: crawler statistics](./statistics.md) for the details.
|
|
1202
|
+
|
|
1203
|
+
## Only if you wrote a custom HTTP client or used `got-scraping` directly
|
|
1204
|
+
|
|
1205
|
+
Applies when you implemented `BaseHttpClient` yourself, or imported `gotScraping` from `@crawlee/utils`. `BaseHttpClient` moved to `@crawlee/http-client` and is built around a single `fetch()` method returning a native `Response`. The `got-scraping` client lives in the opt-in `@crawlee/got-scraping-client` package, and `gotScraping` is no longer exported from `@crawlee/utils`.
|
|
1206
|
+
|
|
1207
|
+
See [Upgrading to v4: HTTP clients](./http-clients.md) for the details.
|
|
1208
|
+
|
|
1209
|
+
## Only if you use `FileDownload`
|
|
1210
|
+
|
|
1211
|
+
Applies when you use the `FileDownload` crawler from `@crawlee/http`.
|
|
1212
|
+
|
|
1213
|
+
### `FileDownload` now extends `BasicCrawler` and takes a slimmer `FileDownloadOptions`
|
|
1214
|
+
|
|
1215
|
+
`FileDownload` was re-based from `HttpCrawler` onto `BasicCrawler`. `FileDownloadOptions` is now `BasicCrawlerOptions<FileDownloadCrawlingContext>` (minus `contextPipelineBuilder`) plus a single `ignoreTlsErrors` flag; `StreamHandlerContext` has been **removed** from `@crawlee/http`. In practice this means the HTTP-crawler-specific options (`navigationTimeoutSecs`, `additionalMimeTypes`, `suggestResponseEncoding`, `forceResponseEncoding`, the `gotOptions`-style `preNavigationHooks`, etc.) are no longer accepted by `FileDownload`; downloading is a thin layer over `BasicCrawler` and the request is performed via `sendRequest` / the configured `httpClient`. If you passed any of those HTTP-only options to `FileDownload`, drop them and configure the `httpClient` (or the request itself) directly. TLS verification changed too: v3 `FileDownload` inherited `ignoreSslErrors: true`, while v4 verifies certificates by default (`ignoreTlsErrors` defaults to `false`). Sessions with a MITM proxy (`session.proxyInfo.ignoreTlsErrors`) still skip verification automatically. To keep the v3 behavior, pass `ignoreTlsErrors: true`. The `FileDownloadCrawlingContext` type also lost its extra type parameter and no longer extends the internal HTTP crawling context — it now extends the common `CrawlingContext` with `contentType`, `request`, and `response`.
|
|
1216
|
+
|
|
1217
|
+
### Crawling context in the `FileDownload` crawler no longer includes `body` and `stream` properties
|
|
1218
|
+
|
|
1219
|
+
The crawling context in the `FileDownload` crawler no longer includes the `body` and `stream` properties. These can be accessed directly via the `response` property instead, e.g. `context.response.bytes()` or `context.response.body`.
|
|
1220
|
+
|
|
1221
|
+
## Only if you use request lists and loaders
|
|
1222
|
+
|
|
1223
|
+
Applies when you use `RequestList` or `SitemapRequestList`, pass `requestList` / `requestQueue` to a crawler, or implement the request loader and manager interfaces yourself. `IRequestList` is now `IRequestLoader` with async counters, `isEmpty()` / `isFinished()` collapsed into `checkReadiness()`, and `SitemapRequestList` is `SitemapRequestLoader`. Crawlers read from a single `requestManager` (the `requestList` / `requestQueue` options still work, but are deprecated), and the new opt-in `ThrottlingRequestManager` can back off per domain on HTTP 429.
|
|
1224
|
+
|
|
1225
|
+
See [Upgrading to v4: request loaders and managers](./request-loaders.md) for the details.
|
|
1226
|
+
|
|
1227
|
+
## Only if you implement a storage backend
|
|
1228
|
+
|
|
1229
|
+
Applies when you implement your own storage backend, or reach below the `Dataset`, `KeyValueStore` and `RequestQueue` frontends. The `StorageBackend` interface (formerly `StorageClient`) needs four classes instead of seven, with async factory methods and slimmer sub-backends. `RequestQueueV1` / `RequestQueueV2` are merged into `RequestQueue`, the `requestLocking` experiment and `requestLockSecs` are gone, and `DatasetClient.listItems()` is replaced by `Dataset.getData()` / `Dataset.values()`.
|
|
1230
|
+
|
|
1231
|
+
See [Upgrading to v4: storage backends](./storage-backends.md) for the details.
|
|
1232
|
+
|
|
1233
|
+
## Only if you tuned autoscaling
|
|
1234
|
+
|
|
1235
|
+
The `minConcurrency` / `maxConcurrency` / `maxRequestsPerMinute` crawler options work as before. This section matters when you used `autoscaledPoolOptions`, drove an `AutoscaledPool` directly, or configured snapshotting and system status. Snapshotting, system status and the scaling logic moved out of `AutoscaledPool`, which is now internal, into a `ConcurrencySystem` that several crawlers can share. `autoscaledPoolOptions` became `taskLoopOptions` and no longer carries concurrency config, and the load-signal options were consolidated into a single `loadSignals` bag.
|
|
1236
|
+
|
|
1237
|
+
See [Upgrading to v4: autoscaling](./autoscaling.md) for the details.
|
|
1238
|
+
|
|
1239
|
+
## Only if you import helpers from `@crawlee/utils` or `@crawlee/types`
|
|
1240
|
+
|
|
1241
|
+
Applies when you import utility functions, enums or types directly from `@crawlee/utils` or `@crawlee/types`, rather than only using the crawlers. The low-level resource-detection helpers are removed, `@crawlee/types` utility types are no longer re-exported from other packages, and several `@crawlee/utils` exports moved to the `@crawlee/utils/internal` entry point or were dropped. `RobotsTxtFile.find()` takes `proxyUrl` in its options, and the HTML-parsing helpers are now asynchronous.
|
|
1242
|
+
|
|
1243
|
+
See [Upgrading to v4: `@crawlee/utils` and `@crawlee/types`](./utils-and-types.md) for the details.
|
|
1244
|
+
|
|
1245
|
+
## Only if you use `JSDOMCrawler` or `LinkeDOMCrawler`
|
|
1246
|
+
|
|
1247
|
+
They moved out of this repository into their own packages, so install them explicitly:
|
|
1248
|
+
|
|
1249
|
+
```bash
|
|
1250
|
+
npm install @crawlee/jsdom @crawlee/linkedom
|
|
1251
|
+
```
|
|
1252
|
+
|
|
1253
|
+
The `crawlee` meta-package no longer re-exports them.
|
|
1254
|
+
|
|
1255
|
+
## Only if you import from `@crawlee/core` directly
|
|
1256
|
+
|
|
1257
|
+
The crawler-only parts of `@crawlee/core` moved to `@crawlee/basic`, so that `@crawlee/core` carries just the storage, request and configuration layer. The moved exports are:
|
|
1258
|
+
|
|
1259
|
+
- autoscaling: `AutoscaledPool`, `Snapshotter`, `SystemStatus`, the `LoadSignal` implementations and their option/snapshot types
|
|
1260
|
+
- crawler internals: `Statistics`, `ErrorTracker`, and the crawling-context types (`CrawlingContext`, `RestrictedCrawlingContext`, `LoadedRequest`, …)
|
|
1261
|
+
- `SessionPool`, `Session` and the session-pool constants
|
|
1262
|
+
- `Router` (with `RouterHandler`, `RouterRoutes` and `defaultRoute`)
|
|
1263
|
+
- the cookie helpers (`mergeCookies`, `getCookiesFromResponse`, …)
|
|
1264
|
+
- `SitemapRequestLoader` (with `SitemapRequestLoaderOptions`)
|
|
1265
|
+
- the `enqueueLinks()` option types (`EnqueueLinksOptions`, `RequestTransform`, `SkippedRequestCallback`) and the URL pattern types (`GlobInput`, `RegExpInput`, …)
|
|
1266
|
+
- the crawler-only error classes `RetryRequestError` and `MissingRouteError`
|
|
1267
|
+
|
|
1268
|
+
`@crawlee/basic` re-exports everything from `@crawlee/core`, so `import { SessionPool } from '@crawlee/basic'` (or from `crawlee`, `@crawlee/http`, `@crawlee/playwright`, …) keeps working unchanged. Only imports written against `@crawlee/core` itself need to be pointed at `@crawlee/basic`.
|
|
1269
|
+
|
|
1270
|
+
## Only if you use `StagehandCrawler`
|
|
1271
|
+
|
|
1272
|
+
### Stagehand type narrowings
|
|
1273
|
+
|
|
1274
|
+
A few Stagehand-specific option types were tightened:
|
|
1275
|
+
|
|
1276
|
+
- `StagehandGotoOptions` dropped its `Dictionary &` intersection — it is now exactly `NonNullable<Parameters<Page['goto']>[1]>`, so arbitrary extra keys are no longer accepted.
|
|
1277
|
+
- The explicit `failedRequestHandler` field was removed from `StagehandCrawlerOptions` (it is inherited from the base crawler options generically, so passing `failedRequestHandler` still works).
|
|
1278
|
+
|
|
1279
|
+
### Removed Stagehand exports and options
|
|
1280
|
+
|
|
1281
|
+
- The `StagehandRequestHandler` type was removed. `StagehandCrawlerOptions.requestHandler` now uses `RequestHandler<StagehandCrawlingContext>` — use that instead.
|
|
1282
|
+
- The `stagehandUtils` namespace was removed. Its only member was internal glue that was never part of the documented surface.
|
|
1283
|
+
- The `AgentResult` re-export was removed. Import it from `@browserbasehq/stagehand` directly — it is a non-optional peer dependency, so it is already installed.
|
|
1284
|
+
- `StagehandLaunchContext.stagehandOptions` was removed. It never had any effect: the value was always overwritten by the `stagehandOptions` option on the crawler and on `stagehandBrowserPool()`. Pass `stagehandOptions` at the top level of the crawler instead, or of `stagehandBrowserPool()` when you supply a `browserPool`.
|
|
1285
|
+
- `StagehandPlugin.stagehandOptions` is now private and `StagehandPlugin.getStagehandForBrowser()` is gone. Reach the `Stagehand` instance through the crawling context's `stagehand` property.
|
|
1286
|
+
|
|
1287
|
+
## Appendix: removed symbols
|
|
1288
|
+
|
|
1289
|
+
The full list of removed exports and members, for ctrl-F purposes, is on the [removed symbols](./removed-symbols.md) page.
|