Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

fix: clean-up cookie handling precedence rules (#3517)

Jindřich Bär1783146a20c6
diff --git a/docs/upgrading/upgrading_v4.md b/docs/upgrading/upgrading_v4.md
index 862f8023b..157071431 100644
--- a/docs/upgrading/upgrading_v4.md
+++ b/docs/upgrading/upgrading_v4.md
@@ -48,6 +48,7 @@ The crawler following options are removed:
- `BrowserCrawler._handleNavigation` (protected)
- `HttpCrawler.userRequestHandlerTimeoutMillis` (protected)
- `HttpCrawler._handleNavigation` (protected)
+- `HttpCrawler._applyCookies` (protected) - cookie merging is now handled by `BaseHttpClient`
- `HttpCrawler._parseHTML` (protected)
- `HttpCrawler._parseResponse` (protected) - made private
- `HttpCrawler.use` and the `CrawlerExtension` class (experimental) - the `ContextPipeline` should be used for extending the crawler
@@ -227,6 +228,30 @@ const config = serviceLocator.getConfiguration();
Do note that the method is currently misnamed - in specific circumstances, it will not return the global configuration object, but the one from the currently active service locator.
+## Cookie handling in `HttpCrawler` and `sendRequest`
+
+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.
+
+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.
+
+The precedence (highest to lowest) is:
+
+1. `sendRequest` `Cookie` header and `cookieJar` overrides
+2. `Cookie` header set directly on the request (via `request.headers`)
+3. Session cookie jar (persisted cookies received from `Set-Cookie` response headers or set manually)
+
+To fully replace the cookie jar for a `sendRequest` call, pass a custom `cookieJar` in the options:
+
+```typescript
+import { CookieJar } from 'tough-cookie';
+
+const jar = new CookieJar();
+await jar.setCookie('my=cookie', request.url);
+const response = await sendRequest({ url: '...' }, { cookieJar: jar });
+```
+
+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.
+
## `transformRequestFunction` precedence in `enqueueLinks`
The `transformRequestFunction` callback in `enqueueLinks` now runs **after** URL pattern filtering (`globs`, `regexps`, `pseudoUrls`) instead of before. This means it has the highest priority and can overwrite any request options set by patterns or the global `label` option.
diff --git a/packages/http-client/src/base-http-client.ts b/packages/http-client/src/base-http-client.ts
index c012a98da..edc65b492 100644
--- a/packages/http-client/src/base-http-client.ts
+++ b/packages/http-client/src/base-http-client.ts
@@ -25,16 +25,36 @@ export abstract class BaseHttpClient implements BaseHttpClientInterface {
private async applyCookies(request: Request, cookieJar: CookieJar): Promise<Request> {
try {
- const cookies = (await cookieJar.getCookies(request.url))
- .map((x) => x.cookieString().trim())
- .filter(Boolean);
+ const requestCookies = request.headers.get('cookie') ?? '';
- if (cookies?.length > 0) {
- request.headers.set('cookie', cookies.join('; '));
+ if (!requestCookies) {
+ // Fast path: no header cookies, use the jar directly.
+ const cookieString = await cookieJar.getCookieString(request.url);
+ if (cookieString) {
+ request.headers.set('cookie', cookieString);
+ }
+ return request;
+ }
+
+ // Merge jar cookies with request Cookie header. Clone the jar so we
+ // don't persist the header-only cookies into the session.
+ const merged = await cookieJar.clone();
+
+ await Promise.all(
+ requestCookies
+ .split(/; */)
+ .filter(Boolean)
+ .map((pair) => merged.setCookie(pair, request.url)),
+ );
+ const cookieString = merged.getCookieStringSync(request.url);
+
+ if (cookieString) {
+ request.headers.set('cookie', cookieString);
}
} catch (e) {
this.log?.warning(`Failed to get cookies for URL "${request.url}": ${(e as Error).message}`);
}
+
return request;
}
diff --git a/packages/http-crawler/src/internals/http-crawler.ts b/packages/http-crawler/src/internals/http-crawler.ts
index 9c6d9fcda..790b05dd2 100644
--- a/packages/http-crawler/src/internals/http-crawler.ts
+++ b/packages/http-crawler/src/internals/http-crawler.ts
@@ -19,7 +19,6 @@ import type {
import {
BasicCrawler,
ContextPipeline,
- mergeCookies,
NavigationSkippedError,
RequestState,
Router,
@@ -418,22 +417,14 @@ export class HttpCrawler<
};
}
- const preNavigationHooksCookies = this._getCookieHeaderFromRequest(request);
-
request.state = RequestState.BEFORE_NAV;
- // Execute pre navigation hooks before applying session pool cookies,
- // as they may also set cookies in the session
await this._executeHooks(this.preNavigationHooks, crawlingContext);
tryCancel();
- const postNavigationHooksCookies = this._getCookieHeaderFromRequest(request);
-
- const cookieString = this._applyCookies(crawlingContext, preNavigationHooksCookies, postNavigationHooksCookies);
-
const proxyUrl = crawlingContext.proxyInfo?.url;
const httpResponse = await addTimeoutToPromise(
- async () => this._requestFunction({ request, session, proxyUrl, cookieString }),
+ async () => this._requestFunction({ request, session, proxyUrl }),
this.navigationTimeoutMillis,
`request timed out after ${this.navigationTimeoutMillis / 1000} seconds.`,
);
@@ -550,37 +541,16 @@ export class HttpCrawler<
return false;
}
- /**
- * Returns the `Cookie` header value based on the current context and
- * any changes that occurred in the navigation hooks.
- */
- protected _applyCookies(
- { session, request }: CrawlingContext,
- preHookCookies: string,
- postHookCookies: string,
- ): string {
- const sessionCookie = session.getCookieString(request.url);
-
- const sourceCookies = [sessionCookie, preHookCookies, postHookCookies];
-
- return mergeCookies(request.url, sourceCookies);
- }
-
/**
* Function to make the HTTP request. It performs optimizations
* on the request such as only downloading the request body if the
* received content type matches text/html, application/xml, application/xhtml+xml.
*/
- protected async _requestFunction({
- request,
- session,
- proxyUrl,
- cookieString,
- }: RequestFunctionOptions): Promise<Response> {
+ protected async _requestFunction({ request, session, proxyUrl }: RequestFunctionOptions): Promise<Response> {
const opts = this._getRequestOptions(request, session, proxyUrl);
try {
- return await this._requestAsBrowser(opts, session, cookieString);
+ return await this._requestAsBrowser(opts, session);
} catch (e) {
if (e instanceof Error && e.constructor.name === 'TimeoutError') {
this._handleRequestTimeout(session);
@@ -656,8 +626,10 @@ export class HttpCrawler<
body: undefined as string | undefined,
};
- // Delete any possible lowercased header for cookie as they are merged in _applyCookies under the uppercase Cookie header
- Reflect.deleteProperty(requestOptions.headers!, 'cookie');
+ if (requestOptions.headers?.cookie || requestOptions.headers?.Cookie) {
+ requestOptions.headers!.Cookie = this._getCookieHeaderFromRequest(request);
+ delete requestOptions.headers!.cookie;
+ }
// Disable SSL verification for MITM proxies
if (session.proxyInfo?.ignoreTlsErrors) {
@@ -762,19 +734,13 @@ export class HttpCrawler<
/**
* @internal wraps public utility for mocking purposes
*/
- private _requestAsBrowser = async (options: Dictionary<any>, session: Session, cookieString?: string) => {
+ private _requestAsBrowser = async (options: Dictionary<any>, session: Session) => {
const opts = processHttpRequestOptions({
...(options as any),
cookieJar: options.cookieJar,
responseType: 'text',
});
- if (cookieString) {
- opts.headers?.delete('Cookie');
- opts.headers?.delete('cookie');
- opts.headers?.set('Cookie', cookieString);
- }
-
const response = await this.httpClient.sendRequest(
new Request(opts.url, {
body: opts.body ? (Readable.toWeb(opts.body) as any) : undefined,
@@ -797,7 +763,6 @@ interface RequestFunctionOptions {
request: CrawleeRequest;
session: Session;
proxyUrl?: string;
- cookieString?: string;
}
/**
diff --git a/test/core/base-http-client.test.ts b/test/core/base-http-client.test.ts
index 4713b19e4..e956ab5b0 100644
--- a/test/core/base-http-client.test.ts
+++ b/test/core/base-http-client.test.ts
@@ -2,15 +2,21 @@ import http from 'node:http';
import type { AddressInfo } from 'node:net';
import { FetchHttpClient } from '@crawlee/http-client';
+import { CookieJar } from 'tough-cookie';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
let server: http.Server;
let url: string;
beforeAll(async () => {
- server = http.createServer((_req, res) => {
- res.setHeader('content-type', 'text/plain');
- res.end('ok');
+ server = http.createServer((req, res) => {
+ if (new URL(req.url!, 'http://localhost').pathname === '/echo-cookies') {
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify({ cookie: req.headers.cookie ?? '' }));
+ } else {
+ res.setHeader('content-type', 'text/plain');
+ res.end('ok');
+ }
});
await new Promise<void>((resolve) =>
@@ -93,3 +99,46 @@ describe('BaseHttpClient signal and timeoutMillis options', () => {
}
});
});
+
+describe('BaseHttpClient cookie handling', () => {
+ test('merges jar cookies with existing Cookie header', async () => {
+ const jar = new CookieJar();
+ await jar.setCookie('jar_cookie=from_jar', `${url}/echo-cookies`);
+ await jar.setCookie('shared=from_jar', `${url}/echo-cookies`);
+
+ const request = new Request(`${url}/echo-cookies`, {
+ headers: { Cookie: 'shared=from_header; header_only=explicit' },
+ });
+
+ const response = await httpClient.sendRequest(request, { cookieJar: jar });
+ const body = (await response.json()) as { cookie: string };
+
+ expect(body.cookie).toContain('header_only=explicit');
+ expect(body.cookie).toContain('jar_cookie=from_jar');
+ // header takes precedence over jar for same-named cookie
+ expect(body.cookie).toContain('shared=from_header');
+ expect(body.cookie).not.toContain('shared=from_jar');
+ });
+
+ test('uses only jar cookies when no Cookie header is set', async () => {
+ const jar = new CookieJar();
+ await jar.setCookie('only_jar=value', `${url}/echo-cookies`);
+
+ const response = await httpClient.sendRequest(new Request(`${url}/echo-cookies`), { cookieJar: jar });
+ const body = (await response.json()) as { cookie: string };
+
+ expect(body.cookie).toBe('only_jar=value');
+ });
+
+ test('preserves Cookie header when jar is empty', async () => {
+ const jar = new CookieJar();
+ const request = new Request(`${url}/echo-cookies`, {
+ headers: { Cookie: 'header_only=value' },
+ });
+
+ const response = await httpClient.sendRequest(request, { cookieJar: jar });
+ const body = (await response.json()) as { cookie: string };
+
+ expect(body.cookie).toBe('header_only=value');
+ });
+});
diff --git a/test/core/crawlers/cheerio_crawler.test.ts b/test/core/crawlers/cheerio_crawler.test.ts
index 097ceb89b..7abc32a63 100644
--- a/test/core/crawlers/cheerio_crawler.test.ts
+++ b/test/core/crawlers/cheerio_crawler.test.ts
@@ -1030,22 +1030,29 @@ describe('CheerioCrawler', () => {
},
]),
- persistCookiesPerSession: false,
sessionPoolOptions: {
maxPoolSize: 1,
},
+ preNavigationHooks: [
+ ({ session, request }) => {
+ // this should get overriden by the server
+ session.setCookie('foo=bar1', request.url);
+ session.setCookie('other=cookie1', request.url);
+
+ request.headers ??= {};
+ request.headers.cookie += '; coo=kie';
+ },
+ ],
requestHandler: ({ json }) => {
responses.push(json);
},
});
- const sessSpy = vitest.spyOn(Session.prototype, 'getCookieString');
- sessSpy.mockReturnValueOnce('foo=bar1; other=cookie1; coo=kie');
await crawler.run();
expect(responses).toHaveLength(1);
expect(responses[0]).toMatchObject({
headers: {
- cookie: 'foo=bar2; other=cookie1; coo=kie; baz=123',
+ cookie: 'foo=bar2; other=cookie1; baz=123; coo=kie',
},
});
});
@@ -1202,6 +1209,35 @@ describe('CheerioCrawler', () => {
expect(responses[0].cookies).toContain('sharedCookie=sharedValue');
expect(responses[1].cookies).toContain('sharedCookie=sharedValue');
});
+
+ test('sendRequest should respect Cookie header override', async () => {
+ const responses: { cookies: string }[] = [];
+
+ const crawler = new CheerioCrawler({
+ requestList: await RequestList.open(null, [
+ { url: `${serverAddress}/special/set-cookie?name=sessionCookie&value=fromSession` },
+ ]),
+ requestHandler: async ({ sendRequest }) => {
+ const withHeader = await sendRequest({
+ url: `${serverAddress}/special/get-cookies`,
+ headers: new Headers({ Cookie: 'custom=override' }),
+ });
+ responses.push((await withHeader.json()) as { cookies: string });
+
+ const withoutOverride = await sendRequest({
+ url: `${serverAddress}/special/get-cookies`,
+ });
+ responses.push((await withoutOverride.json()) as { cookies: string });
+ },
+ });
+
+ await crawler.run();
+ expect(responses).toHaveLength(2);
+ expect(responses[0].cookies).toContain('custom=override');
+ expect(responses[0].cookies).toContain('sessionCookie=fromSession');
+ expect(responses[1].cookies).toContain('sessionCookie=fromSession');
+ expect(responses[1].cookies).not.toContain('custom=override');
+ });
});
describe('Crawling context', () => {