How does Playwright manage cookies?
Short answer: Playwright keeps cookies at the BrowserContext level, not on individual pages. Every page in a context sees the same cookie jar, and a new context starts with an empty one. You work with that jar through three methods on the context: cookies(), addCookies() and clearCookies(). To carry cookies from one test run to the next you save them with storageState().
Read, add and clear cookies
// tests/cookies.spec.ts
import { test, expect } from '@playwright/test';
test('work with the cookie jar', async ({ context, page }) => {
await page.goto('https://shop.example.com/');
// add: each cookie needs either a url, or a domain + path pair
await context.addCookies([
{ name: 'city', value: 'Noida', url: 'https://shop.example.com' },
{
name: 'promo', value: 'DIWALI',
domain: 'shop.example.com', path: '/',
expires: Math.floor(Date.now() / 1000) + 3600, // Unix seconds
},
]);
// read: all cookies, or only those that apply to given URLs
const cookies = await context.cookies('https://shop.example.com');
const city = cookies.find(c => c.name === 'city');
expect(city?.value).toBe('Noida');
// clear: everything, or filter by name, domain or path
await context.clearCookies({ name: 'promo' });
await context.clearCookies();
});
A few details worth knowing from running this kind of test:
cookies()returnsHttpOnlycookies too, such as a server's session id. The page's owndocument.cookiecannot see those, so Playwright is the better place to assert on them.- A cookie added with a
urlthat starts withhttps://is stored assecure: true. - A session cookie (no expiry) comes back with
expires: -1. - Calling
addCookies()with only a name and value fails with "Cookie should have a url or a domain/path pair". - Filtering
clearCookies()by name, domain or path needs a fairly recent Playwright version. On old versions it only clears everything.
Reuse a login with storageState
Logging in through the UI before every test is slow. The usual pattern is to log in once in a setup step, save the context's state to a file, and start every other test from that file. The saved JSON holds cookies and each origin's localStorage.
// tests/auth.setup.ts
import { test as setup, expect } from '@playwright/test';
setup('log in once', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill(process.env.TEST_EMAIL!);
await page.getByLabel('Password').fill(process.env.TEST_PASSWORD!);
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page.getByRole('link', { name: 'My account' })).toBeVisible();
await page.context().storageState({ path: 'playwright/.auth/user.json' });
});
// playwright.config.ts (relevant part)
projects: [
{ name: 'setup', testMatch: /.*\.setup\.ts/ },
{
name: 'chromium',
use: { storageState: 'playwright/.auth/user.json' },
dependencies: ['setup'],
},
],
Add playwright/.auth to .gitignore: the file contains a live session. More patterns are in how Playwright handles authentication in tests.
Why cookies never leak between tests
The test runner gives each test a fresh context, so the cookies a test sets disappear when it finishes. This is the same isolation described in What is a BrowserContext? and how Playwright handles incognito mode. If you need two users with different cookies at once, open two contexts, not two pages.
Common cookie problems
- Cookie added but the site ignores it. The domain or path does not match the URL you visit, or you added a
securecookie and then opened anhttp://page. - Cookie set before navigation is "missing" in the browser. It is there; check with
context.cookies(url)for the exact URL you expect. - Saved login stops working. The server-side session expired. Run the setup project again instead of editing the JSON by hand.
- Tests log each other out in parallel. They share one test account and the server allows only one session. Use a separate account per worker.
Next in this series: what page.route() is used for.
Want to master Playwright hands-on?
Join Uncodemy's Playwright Automation Testing Course in Noida — Dedicated Placement Support.
Explore the Course →