Handling Cookies in Playwright



Handling Cookies in Playwright

Handling cookies is one of the most common tasks in Playwright. Here are the most useful operations with examples.

  1. Get All Cookies

import { test } from ‘@playwright/test’;

test(‘Get all cookies’, async ({ page }) => {

await page.goto(‘https://www.google.com’);

const cookies = await page.context().cookies();

console.log(cookies);

});

Output:

[

{

name: ‘AEC’,

value: ‘abc123’,

domain: ‘.google.com’,

path: ‘/’,

expires: 1780000000,

httpOnly: true,

secure: true,

sameSite: ‘None’

}

]

  1. Get Cookies for Specific URL

const cookies = await page.context().cookies([

‘https://www.google.com’

]);

console.log(cookies);

  1. Add Cookie

await page.context().addCookies([

{

name: ‘username’,

value: ‘Anand’,

domain: ‘example.com’,

path: ‘/’,

httpOnly: false,

secure: false

}

]);

  1. Delete All Cookies

await page.context().clearCookies();

  1. Verify Cookie

const cookies = await page.context().cookies();

const userCookie = cookies.find(c => c.name === ‘username’);

console.log(userCookie);

  1. Check Cookie Value

const cookies = await page.context().cookies();

const session = cookies.find(c => c.name === ‘session’);

console.log(session?.value);

  1. Add Multiple Cookies

await page.context().addCookies([

{

name: ‘language’,

value: ‘en’,

domain: ‘example.com’,

path: ‘/’

},

{

name: ‘theme’,

value: ‘dark’,

domain: ‘example.com’,

path: ‘/’

}

]);

  1. Login Once Using Cookies

After login:

const cookies = await page.context().cookies();

console.log(cookies);

Save them:

import fs from ‘fs’;

fs.writeFileSync(

‘cookies.json’,

JSON.stringify(cookies, null, 2)

);

  1. Reuse Cookies

import fs from ‘fs’;

const cookies = JSON.parse(

fs.readFileSync(‘cookies.json’, ‘utf-8’)

);

await context.addCookies(cookies);

const page = await context.newPage();

await page.goto(‘https://example.com’);

No login required if the session is still valid.

  1. Store Cookies Using Storage State (Recommended)

Playwright recommends using Storage State instead of manually handling cookies.

await page.context().storageState({

path: ‘auth.json’

});

Reuse it:

import { test } from ‘@playwright/test’;

test.use({

storageState: ‘auth.json’

});

This restores:

  • ✅ Cookies
  • ✅ Local Storage
  • ✅ IndexedDB (where applicable)
  1. Print Cookies in Table Format

const cookies = await page.context().cookies();

console.table(cookies);

Example:

┌─────────┬──────────┬────────────┬──────────────┐

│ Name    │ Value    │ Domain     │ Secure       │

├─────────┼──────────┼────────────┼──────────────┤

│ session │ abc123   │ example.com│ true         │

│ theme   │ dark     │ example.com│ false        │

└─────────┴──────────┴────────────┴──────────────┘

  1. Best Practices
  • Use storageState for login/session reuse instead of manually saving cookies.
  • Use context.cookies() to inspect cookies.
  • Use context.addCookies() to inject cookies before navigating to the site.
  • Use context.clearCookies() to test first-time user or logout scenarios.
  • Create a fresh BrowserContext for each test to avoid cookie leakage between tests.

Common Playwright Cookie APIs

Method Purpose
context.cookies() Get cookies
context.addCookies() Add cookies
context.clearCookies() Delete cookies
context.storageState() Save cookies + local storage
test.use({ storageState }) Reuse authenticated session

For more Playwright tutorials, examples, and automation concepts, visit our Playwright Tutorial section.

Tags: ,
Leave a comment

Your email address will not be published. Required fields are marked *

Subscribe now

Receive weekly newsletter with educational materials, new courses, most popular posts, popular books and much more!