DEV Community

Styrow.dev
Styrow.dev

Posted on Originally published at styrow.dev

How do you manage and inject browser cookies in Playwright to simulate pre-authenticated sessions or specific user state

πŸ”₯ Playwright Pro Tip:
Tired of slow, repetitive login flows in your E2E tests? Master Playwright cookie management for lightning-fast, pre-authenticated sessions!

πŸ“Œ Problem Statement
Repetitive UI logins are test bottlenecks. They slow execution, introduce flakiness, and complicate test isolation. Modern test suites demand efficient ways to simulate specific user states or pre-authenticated sessions without burning cycles on UI interactions.

πŸ’‘ Solution & Code Walkthrough
Playwright's storageState() API is your secret weapon. It allows you to capture an authenticated browser state (including cookies, local storage) once, then inject it into subsequent test contexts.

β€’ Phase 1: Capture Authentication State
Perform login once, then save the entire session state to a file. This can be done in a global setup test.

// In global-setup.ts or a specific setup test file
test('setup: save auth state', async ({ page }) => { 
  await page.goto('https://www.example.com/login'); // Your login URL
  await page.fill('#username', 'testuser');
  await page.fill('#password', 'password123');
  await page.click('#login');
  await page.waitForURL('/dashboard'); // Wait for successful redirect
  // Saves cookies & localStorage to a file for later reuse
  await page.context().storageState({ path: 'playwright-auth.json' }); 
});
Enter fullscreen mode Exit fullscreen mode

β€’ Phase 2: Inject Authentication State
Use the saved storageState in new test contexts to start pre-authenticated, skipping the login UI.

// In playwright.config.ts or at the top of your test file
test.use({ storageState: 'playwright-auth.json' }); // Auto-injects session state

test('access protected dashboard', async ({ page }) => {
  await page.goto('https://www.example.com/dashboard'); // Navigates directly as logged in
  await expect(page.locator('h1')).toHaveText('Welcome, testuser!'); 
});
Enter fullscreen mode Exit fullscreen mode

πŸ”‘ Key Takeaways
β€’ Faster Tests: Skip UI login, significantly reducing test duration.
β€’ Increased Reliability: Eliminate flakiness often associated with login interactions.
β€’ Isolated Sessions: Each test gets a clean, pre-authenticated context.
β€’ Full State Management: storageState() captures and restores all session data (cookies, localStorage).

❓ Quick Summary Q&A
Q: Why use storageState() instead of just page.context().addCookies()?
A: storageState() provides a complete snapshot of the browser session (cookies, localStorage), ensuring a fully restored, pre-authenticated user state.

TAGS: playwright, testing, automation, e2e, cookies, sessionmanagement, typescript
────────────────────────────────────────
Ready to level up your testing skills? Download our app for more expert guides, interview prep, and coding challenges!
────────────────────────────────────────

πŸ“² 𝐅𝐑𝐄𝐄 πŒπŽππˆπ‹π„ 𝐀𝐏𝐏 β€” πŸ”πŸŽπŸŽ+ 𝐒𝐃𝐄𝐓 𝐐&𝐀𝐬
Practice real-world interview scenarios offline on the free QA Automation & SDET Prep app:

πŸ€– 𝐆𝐨𝐨𝐠π₯𝐞 𝐏π₯𝐚𝐲 (𝐀𝐧𝐝𝐫𝐨𝐒𝐝):
https://play.google.com/store/apps/details?id=com.app.seleniuminterviewquestions&referrer=utm_source%3Ddevto%26utm_medium%3Darticle%26utm_campaign%3Dselenium_20261020

🍎 𝐀𝐩𝐩 π’π­π¨π«πž (π’πŽπ’):
https://apps.apple.com/app/id6786760948?pt=128640464&ct=devto_selenium_20261020&mt=8

────────────────────────────────────────
────────────────────────────────────────

Top comments (0)