or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cookie-jar.mdcookie-operations.mdindex.mdstores.mdutilities.md

cookie-jar.mddocs/

0

# Cookie Jar Management

1

2

Comprehensive cookie storage and retrieval system with RFC 6265-compliant domain and path matching, expiration handling, security validation, and support for RFC 6265bis features like SameSite attributes and cookie prefixes.

3

4

## Capabilities

5

6

### CookieJar Class

7

8

The main class for cookie storage and retrieval with RFC 6265 compliance and extensive configuration options.

9

10

```typescript { .api }

11

/**

12

* Creates a new CookieJar with optional store and configuration

13

* @param store - Storage backend (defaults to MemoryCookieStore if null/undefined)

14

* @param options - Configuration options or boolean for legacy rejectPublicSuffixes

15

*/

16

class CookieJar {

17

constructor(store?: Store | null, options?: CreateCookieJarOptions | boolean);

18

19

// Properties

20

store: Store;

21

prefixSecurity: string;

22

23

// Cookie management methods (async)

24

setCookie(cookie: string | Cookie, url: string | URL, options?: SetCookieOptions): Promise<Cookie | undefined>;

25

setCookie(cookie: string | Cookie, url: string | URL, callback: Callback<Cookie | undefined>): void;

26

setCookie(cookie: string | Cookie, url: string | URL, options: SetCookieOptions, callback: Callback<Cookie | undefined>): void;

27

28

getCookies(url: string | URL, options?: GetCookiesOptions): Promise<Cookie[]>;

29

getCookies(url: string, callback: Callback<Cookie[]>): void;

30

getCookies(url: string | URL, options: GetCookiesOptions, callback: Callback<Cookie[]>): void;

31

32

getCookieString(url: string | URL, options?: GetCookiesOptions): Promise<string>;

33

getCookieString(url: string, callback: Callback<string | undefined>): void;

34

getCookieString(url: string, options: GetCookiesOptions, callback: Callback<string | undefined>): void;

35

36

getSetCookieStrings(url: string | URL, options?: GetCookiesOptions): Promise<string[] | undefined>;

37

getSetCookieStrings(url: string, callback: Callback<string[] | undefined>): void;

38

getSetCookieStrings(url: string, options: GetCookiesOptions, callback: Callback<string[] | undefined>): void;

39

40

// Synchronous versions (only work with synchronous stores)

41

setCookieSync(cookie: string | Cookie, url: string, options?: SetCookieOptions): Cookie | undefined;

42

getCookiesSync(url: string, options?: GetCookiesOptions): Cookie[];

43

getCookieStringSync(url: string, options?: GetCookiesOptions): string;

44

getSetCookieStringsSync(url: string, options?: GetCookiesOptions): string[];

45

}

46

47

interface CreateCookieJarOptions {

48

rejectPublicSuffixes?: boolean; // Default: true

49

looseMode?: boolean; // Default: false

50

prefixSecurity?: 'strict' | 'silent' | 'unsafe-disabled'; // Default: 'silent'

51

allowSpecialUseDomain?: boolean; // Default: true

52

allowSecureOnLocal?: boolean; // Default: true

53

}

54

```

55

56

**Usage Examples:**

57

58

```typescript

59

import { CookieJar, MemoryCookieStore } from "tough-cookie";

60

61

// Create jar with default memory store

62

const jar = new CookieJar();

63

64

// Create jar with custom configuration

65

const strictJar = new CookieJar(new MemoryCookieStore(), {

66

rejectPublicSuffixes: true,

67

prefixSecurity: 'strict',

68

allowSecureOnLocal: false

69

});

70

71

// Create jar with loose mode for parsing

72

const looseJar = new CookieJar(null, {

73

looseMode: true,

74

prefixSecurity: 'silent'

75

});

76

```

77

78

### Cookie Setting

79

80

Methods for storing cookies in the jar with comprehensive validation.

81

82

```typescript { .api }

83

/**

84

* Attempts to set a cookie in the jar with RFC 6265 validation

85

* @param cookie - Cookie string or Cookie object

86

* @param url - URL where cookie is being set

87

* @param options - Configuration options for setting

88

* @returns Promise resolving to stored Cookie or undefined if rejected

89

*/

90

setCookie(

91

cookie: string | Cookie,

92

url: string | URL,

93

options?: SetCookieOptions

94

): Promise<Cookie | undefined>;

95

96

/**

97

* Synchronous version of setCookie. Only works with synchronous stores

98

* @param cookie - Cookie string or Cookie object

99

* @param url - URL where cookie is being set

100

* @param options - Configuration options for setting

101

* @returns Stored Cookie or undefined if rejected

102

*/

103

setCookieSync(

104

cookie: string | Cookie,

105

url: string,

106

options?: SetCookieOptions

107

): Cookie | undefined;

108

109

interface SetCookieOptions {

110

loose?: boolean;

111

sameSiteContext?: 'strict' | 'lax' | 'none';

112

ignoreError?: boolean;

113

http?: boolean; // Default: true

114

now?: Date;

115

}

116

```

117

118

**Usage Examples:**

119

120

```typescript

121

import { CookieJar } from "tough-cookie";

122

123

const jar = new CookieJar();

124

125

// Set a basic cookie

126

await jar.setCookie('session=abc123', 'https://example.com/');

127

128

// Set cookie with options

129

await jar.setCookie(

130

'csrf=token123; SameSite=Strict; Secure',

131

'https://example.com/',

132

{

133

loose: false,

134

sameSiteContext: 'strict',

135

ignoreError: false

136

}

137

);

138

139

// Set cookie synchronously (if store supports it)

140

const cookie = jar.setCookieSync('user=john', 'https://example.com/');

141

142

// Set cookie with error handling

143

try {

144

await jar.setCookie('__Secure-id=123', 'http://example.com/'); // Will fail due to __Secure- prefix

145

} catch (error) {

146

console.log('Cookie rejected:', error.message);

147

}

148

```

149

150

### Cookie Retrieval

151

152

Methods for retrieving cookies that match specific URLs and contexts.

153

154

```typescript { .api }

155

/**

156

* Retrieves cookies that can be sent for the given URL

157

* @param url - URL to get cookies for

158

* @param options - Options controlling which cookies are returned

159

* @returns Promise resolving to array of matching cookies

160

*/

161

getCookies(url: string | URL, options?: GetCookiesOptions): Promise<Cookie[]>;

162

163

/**

164

* Returns cookies as a Cookie header string

165

* @param url - URL to get cookies for

166

* @param options - Options controlling which cookies are returned

167

* @returns Promise resolving to cookie header string

168

*/

169

getCookieString(url: string | URL, options?: GetCookiesOptions): Promise<string>;

170

171

/**

172

* Returns array of Set-Cookie header strings

173

* @param url - URL to get cookies for

174

* @param options - Options controlling which cookies are returned

175

* @returns Promise resolving to array of Set-Cookie strings

176

*/

177

getSetCookieStrings(url: string | URL, options?: GetCookiesOptions): Promise<string[] | undefined>;

178

179

interface GetCookiesOptions {

180

http?: boolean; // Default: true

181

expire?: boolean; // Default: true (automatically expire old cookies)

182

allPaths?: boolean; // Default: false (include cookies from all paths)

183

sameSiteContext?: 'none' | 'lax' | 'strict';

184

sort?: boolean; // Sort cookies according to RFC 6265

185

}

186

```

187

188

**Usage Examples:**

189

190

```typescript

191

import { CookieJar } from "tough-cookie";

192

193

const jar = new CookieJar();

194

195

// Set some cookies first

196

await jar.setCookie('session=abc123; Path=/', 'https://example.com/');

197

await jar.setCookie('theme=dark; Path=/app', 'https://example.com/app/');

198

await jar.setCookie('csrf=token; SameSite=Strict', 'https://example.com/');

199

200

// Get all matching cookies

201

const cookies = await jar.getCookies('https://example.com/app/');

202

203

// Get cookie header string for HTTP request

204

const cookieHeader = await jar.getCookieString('https://example.com/app/');

205

console.log(cookieHeader); // "session=abc123; theme=dark; csrf=token"

206

207

// Get cookies with specific SameSite context

208

const strictCookies = await jar.getCookies('https://example.com/', {

209

sameSiteContext: 'strict'

210

});

211

212

// Get cookies including all paths

213

const allPathCookies = await jar.getCookies('https://example.com/', {

214

allPaths: true

215

});

216

217

// Get Set-Cookie strings

218

const setCookieStrings = await jar.getSetCookieStrings('https://example.com/');

219

```

220

221

### Serialization and Cloning

222

223

Methods for serializing, deserializing, and cloning cookie jars.

224

225

```typescript { .api }

226

/**

227

* Serializes the CookieJar if the store supports getAllCookies

228

* @returns Promise resolving to serialized jar data

229

*/

230

serialize(): Promise<SerializedCookieJar>;

231

serialize(callback: Callback<SerializedCookieJar>): void;

232

233

/**

234

* Synchronous version of serialize

235

* @returns Serialized jar data or undefined if not supported

236

*/

237

serializeSync(): SerializedCookieJar | undefined;

238

239

/**

240

* Alias for serializeSync()

241

* @returns Serialized jar data or undefined

242

*/

243

toJSON(): SerializedCookieJar | undefined;

244

245

/**

246

* Creates a deep clone of the CookieJar

247

* @param newStore - Optional new store for the clone

248

* @returns Promise resolving to cloned CookieJar

249

*/

250

clone(newStore?: Store): Promise<CookieJar>;

251

clone(callback: Callback<CookieJar>): void;

252

clone(newStore: Store, callback: Callback<CookieJar>): void;

253

254

/**

255

* Synchronous version of clone

256

* @param newStore - Optional new store for the clone

257

* @returns Cloned CookieJar or undefined if not supported

258

*/

259

cloneSync(newStore?: Store): CookieJar | undefined;

260

261

interface SerializedCookieJar {

262

version: string; // tough-cookie version

263

storeType: string | null; // Store constructor name

264

rejectPublicSuffixes: boolean;

265

[key: string]: unknown; // Other configuration

266

cookies: SerializedCookie[]; // Serialized cookies

267

}

268

```

269

270

**Usage Examples:**

271

272

```typescript

273

import { CookieJar } from "tough-cookie";

274

275

const jar = new CookieJar();

276

277

// Add some cookies

278

await jar.setCookie('session=abc123', 'https://example.com/');

279

await jar.setCookie('user=john', 'https://example.com/');

280

281

// Serialize the jar

282

const serialized = await jar.serialize();

283

const jsonString = JSON.stringify(serialized);

284

285

// Clone the jar

286

const clonedJar = await jar.clone();

287

288

// Clone with a different store

289

const customStore = new MemoryCookieStore();

290

const jarWithNewStore = await jar.clone(customStore);

291

292

// Synchronous operations (if store supports it)

293

const syncSerialized = jar.serializeSync();

294

const syncClone = jar.cloneSync();

295

```

296

297

### Static Deserialization Methods

298

299

Static methods for creating CookieJars from serialized data.

300

301

```typescript { .api }

302

/**

303

* Creates a new CookieJar from serialized data

304

* @param strOrObj - Serialized jar string or object

305

* @param store - Optional store for the new jar

306

* @returns Promise resolving to deserialized CookieJar

307

*/

308

static deserialize(strOrObj: string | object, store?: Store): Promise<CookieJar>;

309

static deserialize(strOrObj: string | object, callback: Callback<CookieJar>): void;

310

static deserialize(strOrObj: string | object, store: Store, callback: Callback<CookieJar>): void;

311

312

/**

313

* Synchronous version of deserialize

314

* @param strOrObj - Serialized jar string or object

315

* @param store - Optional store for the new jar

316

* @returns Deserialized CookieJar

317

*/

318

static deserializeSync(strOrObj: string | SerializedCookieJar, store?: Store): CookieJar;

319

320

/**

321

* Alias for deserializeSync

322

* @param jsonString - JSON string or serialized object

323

* @param store - Optional store for the new jar

324

* @returns Deserialized CookieJar

325

*/

326

static fromJSON(jsonString: string | SerializedCookieJar, store?: Store): CookieJar;

327

```

328

329

**Usage Examples:**

330

331

```typescript

332

import { CookieJar } from "tough-cookie";

333

334

// Deserialize from JSON string

335

const jsonString = '{"version":"6.0.0","cookies":[...]}';

336

const jar1 = await CookieJar.deserialize(jsonString);

337

338

// Deserialize with custom store

339

const customStore = new MemoryCookieStore();

340

const jar2 = await CookieJar.deserialize(jsonString, customStore);

341

342

// Synchronous deserialization

343

const jar3 = CookieJar.deserializeSync(jsonString);

344

345

// Using fromJSON alias

346

const jar4 = CookieJar.fromJSON(jsonString);

347

```

348

349

### Cleanup Methods

350

351

Methods for removing cookies from the jar.

352

353

```typescript { .api }

354

/**

355

* Removes all cookies from the jar

356

* @returns Promise that resolves when cleanup is complete

357

*/

358

removeAllCookies(): Promise<void>;

359

removeAllCookies(callback: ErrorCallback): void;

360

361

/**

362

* Synchronous version of removeAllCookies

363

*/

364

removeAllCookiesSync(): void;

365

```

366

367

**Usage Examples:**

368

369

```typescript

370

import { CookieJar } from "tough-cookie";

371

372

const jar = new CookieJar();

373

374

// Add some cookies

375

await jar.setCookie('session=abc123', 'https://example.com/');

376

await jar.setCookie('user=john', 'https://example.com/');

377

378

// Remove all cookies

379

await jar.removeAllCookies();

380

381

// Synchronous cleanup

382

jar.removeAllCookiesSync();

383

384

// Verify cleanup

385

const cookies = await jar.getCookies('https://example.com/');

386

console.log(cookies.length); // 0

387

```

388

389

## Advanced Features

390

391

### SameSite Context Handling

392

393

```typescript

394

import { CookieJar } from "tough-cookie";

395

396

const jar = new CookieJar();

397

398

// Set cookies with different SameSite attributes

399

await jar.setCookie('strict=value; SameSite=Strict', 'https://example.com/');

400

await jar.setCookie('lax=value; SameSite=Lax', 'https://example.com/');

401

await jar.setCookie('none=value; SameSite=None; Secure', 'https://example.com/');

402

403

// Get cookies with specific SameSite context

404

const strictContext = await jar.getCookies('https://example.com/', {

405

sameSiteContext: 'strict' // Only gets cookies appropriate for strict context

406

});

407

408

const laxContext = await jar.getCookies('https://example.com/', {

409

sameSiteContext: 'lax' // Gets cookies appropriate for lax context

410

});

411

```

412

413

### Cookie Prefix Security

414

415

```typescript

416

import { CookieJar, MemoryCookieStore } from "tough-cookie";

417

418

// Strict prefix validation

419

const strictJar = new CookieJar(new MemoryCookieStore(), {

420

prefixSecurity: 'strict'

421

});

422

423

try {

424

// This will throw an error because __Secure- prefix requires HTTPS

425

await strictJar.setCookie('__Secure-id=123; Secure', 'http://example.com/');

426

} catch (error) {

427

console.log('Prefix violation:', error.message);

428

}

429

430

// Silent prefix validation (default)

431

const silentJar = new CookieJar(null, {

432

prefixSecurity: 'silent'

433

});

434

435

// This will silently ignore the invalid cookie

436

const result = await silentJar.setCookie('__Host-id=123', 'http://example.com/');

437

console.log(result); // undefined (cookie was rejected)

438

```

439

440

## Types

441

442

```typescript { .api }

443

interface Callback<T> {

444

(error: Error, result?: never): void;

445

(error: null, result: T): void;

446

}

447

448

interface ErrorCallback {

449

(error: Error | null): void;

450

}

451

452

type SerializedCookie = {

453

key?: string;

454

value?: string;

455

[key: string]: unknown;

456

}

457

```