Loading page...Загружаем страницу...正在加载页面...
AtlasRepo

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

Description and use

Tests become faster and more reliable by using Playwright’s storageState to skip UI login and restore full browser session data.

Problem

Repetitive UI logins are test bottlenecks. They slow execution, introduce flakiness, and complicate test isolation.

Outcome

Tests run faster, become more reliable, and maintain isolated sessions by skipping UI login and restoring full browser state.

Workflow

  • Perform login once and save the session state to a file using page.context().storageState({path:'playwright-auth.json'}) in a global setup test.
  • Configure subsequent tests to use the saved state by setting test.use({storageState:'playwright-auth.json'}) in playwright.config.ts or at the top of the test file.
  • Run tests that navigate directly to protected pages; the browser context is pre-authenticated with the saved cookies and localStorage.
  • Verify user-specific content to confirm the session is correctly restored.
  • Repeat as needed for different user states by creating separate storageState files.

Evidence

Perform login once, then save the entire session state to a file. This can be done in a global setup test.

Source

Use the saved storageState in new test contexts to start pre-authenticated, skipping the login UI.

Source

Faster Tests: Skip UI login, significantly reducing test duration.

Source

Increased Reliability: Eliminate flakiness often associated with login interactions.

Source

  • Record date: 2026-10-20T12:56:16.561Z