Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Principle:Microsoft Playwright Save and Load Authentication State

From Leeroopedia
Knowledge Sources
Domains Browser_Automation, CLI
Last Updated 2026-02-11 00:00 GMT

Overview

Persisting and restoring browser authentication state (cookies, local storage) across automation sessions to avoid re-authentication.

Description

Web applications typically authenticate users through a combination of cookies, local storage tokens, and session identifiers. When automating browsers, each new browser context starts with a clean slate -- no cookies, no local storage, no active sessions. This means that every automation run would need to repeat the full login flow, which is slow, flaky, and places unnecessary load on authentication infrastructure.

Save and Load Authentication State is the principle of capturing the browser's authentication artifacts at the end of a session and restoring them at the start of the next session, effectively "fast-forwarding" past the login step.

The state to persist typically includes:

  • Cookies -- Session cookies, authentication tokens, CSRF tokens, and consent preferences, each with their domain, path, expiry, and security flags.
  • Local storage -- Per-origin key-value pairs that many single-page applications use to store JWT tokens, user preferences, and session metadata.
  • Origins -- The set of origins whose local storage is captured, ensuring state is scoped correctly.

The persistence format is a JSON file containing a structured representation of all cookies and per-origin local storage entries. This file can be:

  • Generated manually (e.g., by logging in interactively and saving state).
  • Generated by a setup script that runs once before a test suite.
  • Shared across team members or CI runners to avoid redundant authentication.
  • Version-controlled (with appropriate security precautions) for deterministic test environments.

Usage

Apply this principle whenever:

  • Multiple automation sessions need to run as an authenticated user without repeating the login flow each time.
  • A CI pipeline has a global setup step that authenticates once and shares the state with all subsequent test workers.
  • A developer wants to interactively log in once, save the state, and then use it for repeated screenshot captures or code generation sessions.
  • Testing needs to verify behavior for different user roles by loading different pre-saved authentication states.

Theoretical Basis

Authentication state persistence follows a save-then-restore pattern:

PHASE 1: SAVE (after authentication)
  1. USER completes login flow in the browser (manually or via automation)
  2. EXTRACT state from the browser context:
     cookies = context.cookies()
     localStorage = FOR EACH origin: collect all key-value pairs
  3. SERIALIZE state to JSON:
     {
       "cookies": [ { name, value, domain, path, expires, httpOnly, secure, sameSite }, ... ],
       "origins": [
         {
           "origin": "https://example.com",
           "localStorage": [ { name, value }, ... ]
         },
         ...
       ]
     }
  4. WRITE JSON to a file

PHASE 2: LOAD (before automation)
  1. READ JSON from the file
  2. CREATE browser context with the deserialized state:
     context = browser.newContext({ storageState: pathToJsonFile })
  3. The context now has all cookies and localStorage pre-populated
  4. Subsequent navigations to authenticated pages succeed without login

Key design considerations:

  • Serialization completeness -- The saved state must include all cookie attributes (not just name/value) to ensure correct domain scoping, expiry behavior, and security flag handling.
  • Origin scoping -- Local storage is scoped per origin. The serialized state must preserve this scoping so that tokens are restored to the correct origin.
  • State freshness -- Saved state has a limited lifetime defined by cookie expiry and server-side session validity. Stale state files must be regenerated.
  • Security -- State files contain authentication credentials. They should be treated as secrets: excluded from version control, stored securely, and rotated regularly.
  • Composability -- The load operation should accept either a file path or an inline object, allowing flexible integration with test setup frameworks.

Related Pages

Implemented By

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment