Crawlee v4: Untangled
Crawlee v4 is out. It's the first major release since July 2022, and most of the work went into the public contract: fewer internals to reach into, objects you pass in where there used to be option bags, and standard types where Crawlee had its own. This post covers what you get. The upgrading guide covers what changed.
- Installing and upgrading
- Remote browsers
- Storage writes are transactional
- impit is the default HTTP client
- A session is a whole identity
- Timeouts that mean what they say
- Polite crawling
- One concurrency budget for several crawlers
- Crawlers stop stepping on each other
- Storage backends
- Leaning on standards
- Interfaces instead of options
- Smaller improvements
- In case you skipped a few 3.x releases
- Upgrading
Installing and upgrading
Starting a new project:
npm install crawlee@latest
Upgrading an existing one from v3:
npx @crawlee/upgrade@latest
This prints a prompt for your coding agent. Details are in the upgrading section below.
Crawlee v4 needs Node.js 22.15 or newer and is published as native ESM. A CommonJS project can still require() it. Use TypeScript 5.9 or newer for type checking. The install got smaller along the way: npm install crawlee pulls in 199 packages and 67 MB, down from 293 packages and 106 MB in v3.
Remote browsers
PlaywrightCrawler and PuppeteerCrawler can connect to a browser running somewhere else, on any service that exposes a WebSocket or CDP endpoint. The crawler keeps managing sessions, retries, and the request lifecycle.
const crawler = new PlaywrightCrawler({
remoteBrowser: {
endpoint: `wss://browser.example.com?token=${token}`,
// stay within the service's limit of concurrent sessions
maxOpenBrowsers: 5,
},
requestHandler,
});
The remote browser guide covers services that need a session created and released around each connection.
Storage writes are transactional
Consider a handler that stores two items and can fail between them:
const crawler = new CheerioCrawler({
async requestHandler({ $, pushData }) {
await pushData(extractProduct($));
if ($('.captcha').length > 0) throw new Error('Blocked');
await pushData(extractReviews($));
},
});
In v3, every failed attempt left a product in the dataset, so a request that succeeded on its third try stored the product three times. In v4, each request runs in a storage transaction. Dataset and key-value store writes are applied when the handler succeeds, and a handler that throws leaves nothing behind.
Requests you enqueue are still added right away and deduplicated by uniqueKey. If you need a write to land immediately, wrap it in withDirectStorageAccess(). If you want to turn this off across your entire crawler, set transactionalStorage: false in your crawler configuration. The result storage guide explains this in detail.
impit is the default HTTP client
HttpCrawler, CheerioCrawler, and sendRequest() now send their requests with impit instead of got-scraping. impit is an HTTP client written in Rust that impersonates a browser. Its TLS handshake and headers match a real browser's, over HTTP/1.1, HTTP/2, or HTTP/3. In Crawlee, the session's fingerprint decides which browser it imitates, so a new session is a new, consistent identity.
It also uses the Fetch API. context.response and the result of sendRequest() are native Response objects:
const crawler = new CheerioCrawler({
async requestHandler({ request, response, sendRequest }) {
if (response.status === 404) return;
const apiResponse = await sendRequest({
url: `${request.loadedUrl}.json`,
headers: { accept: 'application/json' },
});
const data = await apiResponse.json();
},
});
sendRequest() sends the session's cookies for you and respects a Cookie header you set yourself.
got-scraping has reached its end of life and won't receive further updates. If you can't switch yet, the opt-in @crawlee/got-scraping-client package keeps it working in v4. Move to impit when you can, and tell us where it falls short. Any other client works too as long as it implements a single fetch()-shaped method.
A session is a whole identity
In v3, the three things that make up a scraper's identity were configured in three places: the proxy in proxyConfiguration, the fingerprint in browserPoolOptions, the cookies in the session. They had separate lifecycles, and proxy tiers and maxSessionRotations existed to work around that.
In v4, a session carries its proxy, cookies, and fingerprint, and when it gets blocked all three are retired together. Every crawler uses a session pool. Session errors no longer have a retry budget of their own. They count toward maxRequestRetries.
For most projects, passing proxyConfiguration to the crawler is still all there is to it. When you want to decide what a fresh identity looks like, build the pool yourself:
import { CheerioCrawler, Session, SessionPool } from 'crawlee';
const sessionPool = new SessionPool({
sessionOptions: { maxUsageCount: 20 },
createSessionFunction: async (options) =>
new Session({
...options?.sessionOptions,
proxyInfo: await proxyConfiguration.newProxyInfo(options?.sessionOptions?.proxyInfo),
}),
});
const crawler = new CheerioCrawler({ sessionPool, requestHandler });
Timeouts that mean what they say
In v3, navigation ran inside the request handler's time window and the two limits were added up, plus a ten-second buffer. Set requestHandlerTimeoutSecs: 60 on a PlaywrightCrawler, let a navigation hook hang, and the request failed after 130 seconds with a message that blamed the request handler.
In v4 the two phases are timed separately. requestHandlerTimeoutSecs covers your handler and nothing else. navigationTimeoutSecs covers the navigation together with its hooks. A route can have its own limit, and a handler can ask for more time once it knows how much work it has:
import { createPlaywrightRouter } from 'crawlee';
const router = createPlaywrightRouter();
router.addHandler(
'LIST',
async ({ enqueueLinks }) => {
await enqueueLinks({ label: 'DETAIL' });
},
{ requestHandlerTimeoutSecs: 120 },
);
router.addHandler('DETAIL', async ({ page, extendTimeout }) => {
const reviewPages = await page.locator('.pagination a').count();
extendTimeout(reviewPages * 10);
});
Polite crawling
Crawlee could already skip what a site's robots.txt disallows. v4 adds the other half of being a well-behaved visitor, which is slowing down when a site asks you to. In v3 a robots.txt Crawl-delay wasn't enforced at all, and an HTTP 429 only retired the session and retried right away.
The new ThrottlingRequestManager paces each domain separately:
import { CheerioCrawler, ThrottlingRequestManager } from 'crawlee';
const crawler = new CheerioCrawler({
respectRobotsTxtFile: true,
// Needed for `Crawl-delay` and 429 backoff. Without it, the crawler
// doesn't pace the domain and logs a warning that says so.
requestManager: new ThrottlingRequestManager({ domains: 'all' }),
requestHandler,
});
Crawl-delayis honored. WithrespectRobotsTxtFileon, requests to a domain are spaced by the delay its robots.txt asks for.- A 429 is treated as a rate limit. The crawler waits for the time given in
Retry-After, or backs off exponentially when there is none. The retry doesn't count againstmaxRequestRetries, and the session is left alone. - Only that domain waits. Requests to every other domain keep going at full speed.
You can list specific domains instead of 'all'. Setting sameDomainDelaySecs also works. The crawler then creates the manager itself, with that delay as the minimum.
One concurrency budget for several crawlers
In v3, each crawler had its own autoscaled pool. Two crawlers with maxConcurrency: 20 ran up to 40 tasks on the same CPU and memory. The new ConcurrencySystem measures the load and enforces one limit for every crawler that shares it:
import { CheerioCrawler, ConcurrencySystem, PlaywrightCrawler } from 'crawlee';
const concurrencySystem = new ConcurrencySystem({ maxConcurrency: 20 });
await concurrencySystem.start();
const http = new CheerioCrawler({ concurrencySystem, requestHandler });
const browser = new PlaywrightCrawler({ concurrencySystem, requestHandler });
await Promise.all([http.run(listUrls), browser.run(detailUrls)]);
await concurrencySystem.stop();
Because you hold the object, you can also change its limits while the crawl runs, or give it load signals of your own.
Crawlers stop stepping on each other
Two crawlers in one v3 process shared the default request queue unless you gave each its own, so an HTTP crawler and a browser crawler could consume each other's requests. In v4 the first crawler you create gets the default queue and every other one gets a queue of its own.
Calling run() a second time was already possible in v3, but what it did depended on where you ran it. With local storage it emptied the default queue first and crawled the same URLs again. With any other storage it kept the queue and crawled nothing. In v4 it does the same thing everywhere: nothing is purged between runs, a request that was already handled isn't crawled again, and requests you add are.
{
await using crawler = new PlaywrightCrawler({ requestHandler });
await crawler.run(startUrls);
await crawler.addRequests(moreUrls);
await crawler.run();
} // the browser pool is destroyed here
The crawler also keeps its browser pool between runs now and releases it when you dispose of the crawler. await using does that for you, and it works on Node.js 22+ when TypeScript compiles it. In plain JavaScript, call crawler.destroy().
Storage backends
The v3 MemoryStorage was the default file system storage that could also be told to stay in memory. v4 splits it in two. FileSystemStorageBackend is the default and always persists. MemoryStorageBackend never touches the disk. A crawler can be given a backend of its own, which then holds its request queue, datasets, and key-value stores:
import { CheerioCrawler, MemoryStorageBackend } from 'crawlee';
const crawler = new CheerioCrawler({
storageBackend: new MemoryStorageBackend(),
requestHandler,
});
If you maintain a custom backend, the contract is four classes now, down from seven.
Leaning on standards
Crawlee v3 had its own answer to several questions the JavaScript ecosystem has since settled. v4 uses the common answer wherever there is one:
- Fetch API. Responses are native
Responseobjects, and a custom HTTP client implements a singlefetch()-shaped method, as described above. - Zod for validation. Crawlee checks its own options with Zod, and reports every problem at once instead of the first one.
- Standard Schema. Wherever you hand Crawlee a schema, such as for a route's
userData, it accepts anything that implements Standard Schema. - Globs and regular expressions. The
includeoption ofenqueueLinks()replacesglobs,regexps, and Crawlee's own pseudo-URL syntax. - Explicit resource management. Crawlers, pools, and the concurrency system implement
Symbol.asyncDispose, soawait usingshuts them down.
Interfaces instead of options
A v3 crawler created its collaborators itself and repeated their options: sessionPoolOptions, browserPoolOptions, autoscaledPoolOptions, statisticsOptions. That works for changing a number. Changing behavior usually meant subclassing, and the extension points were protected methods with underscores in their names.
In v4 you pass the structure in:
| v3 | v4 |
|---|---|
useSessionPool, sessionPoolOptions | sessionPool: ISessionPool |
browserPoolOptions | browserPool: IBrowserPool |
statisticsOptions | statistics: IStatistics |
requestList and requestQueue | requestManager: IRequestManager |
autoscaledPoolOptions | concurrencySystem: IConcurrencySystem |
log | logger: CrawleeLogger |
httpClient shaped after got-scraping | httpClient: IHttpClient |
Leave an option out and the crawler builds the default, and tears it down when the crawler is destroyed. Pass your own and the crawler uses it as it is, but you're responsible for tearing it down at the end.
The crawling context follows the same idea. extendContext adds members to it, and they are typed in every hook and handler:
const crawler = new CheerioCrawler({
extendContext: () => ({ db }),
async requestHandler({ $, db }) {
await db.save({ title: $('title').text() });
},
});
This is also why v4 has so many breaking changes. The number of protected members in the public API went down by roughly two thirds, and members that start with an underscore went from 160 to 21.
Smaller improvements
- Run-scoped storages.
Dataset.open({ alias: 'rejected' })gives you an unnamed storage that lives for the run and is purged on the next start, like the default one. Key-value stores and request queues take an alias too. - Skipping a request.
skipRequest()on the crawling context marks the request as handled without counting it as a failure. It replaces thenoRetry-and-throw workaround. - Links without enqueueing.
extractLinks()returns the URLs thatenqueueLinks()would have added. - Microdata.
extractMicrodata()in@crawlee/utilsreads schema.org microdata from HTML or a Cheerio object. - OpenTelemetry. The new
@crawlee/otelpackage traces request handling and forwards Crawlee logs to any OpenTelemetry backend.
In case you skipped a few 3.x releases
A lot shipped in minor releases since 3.0. All of it is in v4, some under a new name:
AdaptivePlaywrightCrawler, which decides per page whether it needs a browser (3.8)StagehandCrawlerfor AI-driven browser automation (3.16)- pluggable HTTP clients (3.12), which made
impitpossible - type-safe router labels and schema validation of
userData(3.18) - robots.txt and sitemap support: parsing utilities (3.7), a sitemap-backed request source (3.11),
discoverValidSitemaps()(3.16) handleCloudflareChallenge()(3.13)- shadow DOM and iframe expansion in
parseWithCheerio()(3.9, 3.11) FileDownloadand error snapshots (3.10)maxCrawlDepth(3.14) andsameDomainDelaySecs(3.5)- async iterators for
DatasetandKeyValueStore(3.16) - custom load signals for autoscaling (3.17)
Upgrading
The upgrading guide starts with a cheat sheet of renames and the changes most projects will hit. The rest is split into sections that only apply if you use what their title names.
If you work with a coding agent, let it do the first pass. This prints a migration prompt to hand over:
npx @crawlee/upgrade@latest
A passing type check isn't the end, though. These changes compile and behave differently:
- HTTP crawlers verify TLS certificates. Set
ignoreTlsErrors: trueto get the v3 behavior back. - Blocked requests share the retry budget with every other failure. Raise
maxRequestRetriesif you relied on session rotations. - Navigation hooks count against
navigationTimeoutSecs, which is 30 seconds for HTTP crawlers. - The default HTTP client is a different one, so compare block rates on your target site.
npm install --omit=optionalskips the native binaries ofimpitand the file system storage. Remove the flag from your Dockerfile.
If your project runs on Apify, upgrade the apify package to v4 in the same step. It has an upgrading guide of its own.
Crawlee v3 keeps receiving fixes for high- and critical-severity vulnerabilities for twelve months. New features and other fixes land in v4.
That's it for v4. It took a little over 500 commits, and more than 30 people from the community contributed to it. Thank you. The full list of changes is in the changelog on GitHub. If you run into problems or have questions, open a GitHub discussion or join the Crawlee Discord.