@@ -23,7 +23,7 @@ import type { Awaitable, Dictionary } from '@crawlee/types';
2323import type { RequestLike , ResponseLike } from 'content-type' ;
2424import contentTypeParser from 'content-type' ;
2525import mime from 'mime-types' ;
26- import type { OptionsInit , Method , Request as GotRequest , Response as GotResponse , GotOptionsInit } from 'got-scraping' ;
26+ import type { OptionsInit , Method , Request as GotRequest , Response as GotResponse , GotOptionsInit , Options } from 'got-scraping' ;
2727import { gotScraping , TimeoutError } from 'got-scraping' ;
2828import type { JsonValue } from 'type-fest' ;
2929import { extname } from 'node:path' ;
@@ -539,7 +539,10 @@ export class HttpCrawler<Context extends InternalHttpCrawlingContext<any, any, H
539539 gotOptions . headers ??= { } ;
540540 Reflect . deleteProperty ( gotOptions . headers , 'Cookie' ) ;
541541 Reflect . deleteProperty ( gotOptions . headers , 'cookie' ) ;
542- gotOptions . headers . Cookie = mergedCookie ;
542+
543+ if ( mergedCookie !== '' ) {
544+ gotOptions . headers . Cookie = mergedCookie ;
545+ }
543546 }
544547
545548 /**
@@ -551,7 +554,7 @@ export class HttpCrawler<Context extends InternalHttpCrawlingContext<any, any, H
551554 const opts = this . _getRequestOptions ( request , session , proxyUrl , gotOptions ) ;
552555
553556 try {
554- return await this . _requestAsBrowser ( opts ) ;
557+ return await this . _requestAsBrowser ( opts , session ) ;
555558 } catch ( e ) {
556559 if ( e instanceof TimeoutError ) {
557560 this . _handleRequestTimeout ( session ) ;
@@ -729,10 +732,21 @@ export class HttpCrawler<Context extends InternalHttpCrawlingContext<any, any, H
729732 /**
730733 * @internal wraps public utility for mocking purposes
731734 */
732- private _requestAsBrowser = ( options : OptionsInit & { isStream : true } ) => {
735+ private _requestAsBrowser = ( options : OptionsInit & { isStream : true } , session ?: Session ) => {
733736 return new Promise < IncomingMessage > ( ( resolve , reject ) => {
734737 const stream = gotScraping ( options ) ;
735738
739+ stream . on ( 'redirect' , ( updatedOptions : Options , redirectResponse : IncomingMessage ) => {
740+ if ( this . persistCookiesPerSession ) {
741+ session ! . setCookiesFromResponse ( redirectResponse ) ;
742+
743+ const cookieString = session ! . getCookieString ( updatedOptions . url ! . toString ( ) ) ;
744+ if ( cookieString !== '' ) {
745+ updatedOptions . headers . Cookie = cookieString ;
746+ }
747+ }
748+ } ) ;
749+
736750 stream . on ( 'error' , reject ) ;
737751 stream . on ( 'response' , ( ) => {
738752 resolve ( addResponsePropertiesToStream ( stream ) ) ;
0 commit comments