Back to All Questions
Question 73 of 100
Authentication
Intermediate
How do cookies and local storage work in Playwright contexts?
The Answer
Cookies and storage are scoped to the `BrowserContext`. New contexts start clean. You can add, read, and delete cookies/storage programmatically within tests.
Deep Dive Explanation
Pre-seeding cookies via `context.addCookies()` is faster than logging in via the UI, but less realistic. The best approach is `storageState` (which combines both cookies and localStorage). Use direct cookie manipulation sparingly β only for edge cases like testing cookie expiry.
example.spec.ts
// COOKIES
// Add cookies to context
await context.addCookies([{
name: 'session_id',
value: 'abc-123',
domain: 'app.com',
path: '/',
}]);
// Read cookies
const cookies = await context.cookies();
const sessionCookie = cookies.find(c => c.name === 'session_id');
// Clear all cookies
await context.clearCookies();
// LOCAL STORAGE (via evaluate)
await page.evaluate(() => {
localStorage.setItem('theme', 'dark');
localStorage.setItem('lang', 'en');
});
const theme = await page.evaluate(() => localStorage.getItem('theme'));
console.log(theme); // 'dark'