🔐 The "Log In Once" Principle: Storage State Persistence
In traditional test suites, every individual test scenario starts by typing credentials into login inputs, solving multi-factor authentication checkpoints, or waiting for auth redirects. When running hundreds of test cases, this repetitive authentication tax adds tens of minutes of execution time and introduces substantial test flakiness. Playwright solves this fundamentally with Storage State persistence. An authenticated web session consists strictly of cookies and HTML5 LocalStorage / SessionStorage. Playwright captures this complete snapshot to a compact JSON file via context.storage_state(path=...). Any subsequent test can initialize a BrowserContext using browser.new_context(storage_state=...), opening browser tabs instantly in a pre-authenticated state with zero UI login forms.
STORAGE STATE LIFECYCLE:
[ PHASE 1: GLOBAL SETUP (Runs Once in conftest / setup script) ]
1. Launch clean context ──► Navigate to login form
2. Submit credentials ──► Server issues JWT cookie & sets LocalStorage
3. context.storage_state(path="playwright/.auth/admin_state.json")
4. Close setup context
│
▼ (Saves cookies + localStorage origins to JSON file on disk)
[ PHASE 2: PARALLEL TEST WORKERS (Run 100+ Tests Concurrently) ]
├── Test 1: browser.new_context(storage_state=".../admin_state.json") ──► Opens /dashboard (Pre-auth!)
├── Test 2: browser.new_context(storage_state=".../admin_state.json") ──► Opens /settings (Pre-auth!)
└── Test 3: browser.new_context(storage_state=".../admin_state.json") ──► Opens /reports (Pre-auth!)
context.storage_state(path=...).
import os
import tempfile
from playwright.sync_api import sync_playwright, expect
auth_json_path = os.path.join(tempfile.gettempdir(), "admin_session.json")
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
page = context.new_page()
# Simulated secure login portal
page.set_content("""
""")
# Fill and submit form
page.locator("#user").fill("pooja_patil")
page.locator("#pass").fill("SecureEnterprise2026!")
page.locator("#login-btn").click()
# Auto-waiting assertion verifies login completion before state snapshot
expect(page.locator("#welcome")).to_be_visible()
# Capture storage state snapshot to file
context.storage_state(path=auth_json_path)
print(f"Authentication snapshot saved successfully to: {auth_json_path}")
print(f"File size on disk: {os.path.getsize(auth_json_path)} bytes")
context.close()
browser.close()
storage_state="admin_session.json". Navigate directly to internal routes without executing any login steps.
from playwright.sync_api import sync_playwright, expect
# Pointing to the saved storage state captured in Example 1
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
# 1. Initialize context with saved storage state
context = browser.new_context(storage_state=auth_json_path)
page = context.new_page()
# Simulated dashboard that checks for active session tokens
page.set_content("""
Protected Analytics Dashboard
Checking session...
""")
status_tag = page.locator("#auth-status")
expect(status_tag).to_have_text("AUTHORIZED_ADMIN_ACCESS")
print(f"Verified pre-authenticated state in fresh context: '{status_tag.inner_text()}'")
print("Page accessed protected data immediately with zero form interaction!")
context.close()
browser.close()
cookies and origins (where each origin encapsulates localStorage key-value pairs).
{
"cookies": [
{
"name": "app_session_id",
"value": "SESS_NIKITA_99214",
"domain": "nikita-infotech.com",
"path": "/",
"expires": 1793364000.5,
"httpOnly": true,
"secure": true,
"sameSite": "Lax"
}
],
"origins": [
{
"origin": "https://nikita-infotech.com",
"localStorage": [
{
"name": "jwt_token",
"value": "JWT_POOJA_LEAD_2026_XYZ"
},
{
"name": "user_role",
"value": "Administrator"
}
]
}
]
}
admin_state.json, editor_state.json, customer_state.json) to test role-based access control (RBAC).
import os
import json
import tempfile
from playwright.sync_api import sync_playwright
auth_dir = os.path.join(tempfile.gettempdir(), "playwright_auth")
os.makedirs(auth_dir, exist_ok=True)
admin_file = os.path.join(auth_dir, "admin_state.json")
customer_file = os.path.join(auth_dir, "customer_state.json")
# Helper to synthesize multi-role state files programmatically
def create_mock_state_file(target_path: str, role: str, token: str):
state_payload = {
"cookies": [{"name": "auth_role", "value": role, "domain": "example.com", "path": "/"}],
"origins": [{
"origin": "https://example.com",
"localStorage": [{"name": "auth_token", "value": token}, {"name": "role", "value": role}]
}]
}
with open(target_path, "w") as f:
json.dump(state_payload, f, indent=2)
create_mock_state_file(admin_file, "Admin", "TOKEN_ADMIN_PRIVILEGED")
create_mock_state_file(customer_file, "Customer", "TOKEN_CUSTOMER_STANDARD")
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
# 1. Launch test using Admin state
admin_ctx = browser.new_context(storage_state=admin_file)
p1 = admin_ctx.new_page()
p1.goto("https://example.com")
admin_role = p1.evaluate("() => localStorage.getItem('role')")
print(f"Context 1 Initialized with Role: '{admin_role}'")
# 2. Launch test in parallel using Customer state
cust_ctx = browser.new_context(storage_state=customer_file)
p2 = cust_ctx.new_page()
p2.goto("https://example.com")
cust_role = p2.evaluate("() => localStorage.getItem('role')")
print(f"Context 2 Initialized with Role: '{cust_role}'")
assert admin_role == "Admin"
assert cust_role == "Customer"
admin_ctx.close()
cust_ctx.close()
browser.close()
context.storage_state() without arguments to return the state as a native Python dictionary in memory, ideal for dynamic test pipelines and stateless CI environments.
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
# Source context establishes session
source_context = browser.new_context()
page = source_context.new_page()
page.goto("https://example.com")
page.evaluate("() => localStorage.setItem('ephemeral_token', 'TOKEN_MEMORY_5510')")
# Returns native Python dict representing storage state
in_memory_state = source_context.storage_state()
source_context.close()
print("In-Memory Storage State Captured:")
print(f" Origins Count : {len(in_memory_state['origins'])}")
print(f" First Key/Val : {in_memory_state['origins'][0]['localStorage'][0]}")
# Pass in-memory dictionary directly into a new context
target_context = browser.new_context(storage_state=in_memory_state)
target_page = target_context.new_page()
target_page.goto("https://example.com")
token_read = target_page.evaluate("() => localStorage.getItem('ephemeral_token')")
print(f"Target context read in-memory token: '{token_read}'")
assert token_read == "TOKEN_MEMORY_5510"
target_context.close()
browser.close()
conftest.py that logs in once before any tests run, saving auth.json for the entire suite to consume.
# content of conftest.py
import os
import pytest
from playwright.sync_api import Playwright, Browser
AUTH_FILE = "playwright/.auth/user_session.json"
@pytest.fixture(scope="session", autouse=True)
def global_authentication_setup(playwright: Playwright):
"""Logs in once before any tests run and saves storage state."""
os.makedirs(os.path.dirname(AUTH_FILE), exist_ok=True)
# Only perform login if auth file does not exist or has expired
if not os.path.exists(AUTH_FILE):
browser = playwright.chromium.launch(headless=True)
context = browser.new_context()
page = context.new_page()
# Execute login steps once
page.goto("https://example.com")
page.evaluate("""() => {
document.cookie = 'auth_session=ACTIVE_VALIDATED; path=/';
localStorage.setItem('auth_user', 'Aarav Sharma');
}""")
context.storage_state(path=AUTH_FILE)
context.close()
browser.close()
print("\n[Global Setup] Authentication completed and saved to auth.json")
@pytest.fixture
def authenticated_context(browser: Browser):
"""Yields a pre-authenticated BrowserContext for individual tests."""
context = browser.new_context(storage_state=AUTH_FILE)
yield context
context.close()
context.clear_cookies() and clear_permissions().
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
# Establish initial cookies
context.add_cookies([
{"name": "session_id", "value": "SESS_99124", "domain": "example.com", "path": "/"},
{"name": "tracking_pref", "value": "opt_out", "domain": "example.com", "path": "/"}
])
print(f"Initial Cookies Count: {len(context.cookies())}")
# Clear all active session cookies on the context
context.clear_cookies()
print(f"Cookies Count after context.clear_cookies(): {len(context.cookies())}")
# Navigate to page and verify session is gone
page = context.new_page()
page.goto("https://example.com")
# Clear localStorage explicitly using evaluate
page.evaluate("() => localStorage.clear()")
print("LocalStorage cleared successfully via page.evaluate()")
context.close()
browser.close()
expires timestamp inside storage_state.json, refreshing the authentication snapshot if the session has lapsed.
import os
import json
import time
from playwright.sync_api import sync_playwright
def is_storage_state_valid(state_file: str) -> bool:
"""Returns True if state file exists and cookies have not expired."""
if not os.path.exists(state_file):
return False
try:
with open(state_file, "r") as f:
data = json.load(f)
cookies = data.get("cookies", [])
current_time = time.time()
for cookie in cookies:
# If cookie has an expires field and it has passed, state is stale
if "expires" in cookie and cookie["expires"] != -1 and cookie["expires"] < current_time:
return False
return True
except Exception:
return False
# Demonstration of check
demo_file = os.path.join(tempfile.gettempdir(), "check_state.json")
with open(demo_file, "w") as f:
json.dump({"cookies": [{"name": "auth", "value": "1", "expires": time.time() + 3600}]}, f)
print(f"Is Storage State currently valid? {is_storage_state_valid(demo_file)}")
if os.path.exists(demo_file):
os.remove(demo_file)
PLAYWRIGHT STORAGE STATE API MATRIX:
┌──────────────────────────────┬──────────────────────────────┬─────────────────────────────────────────────────────────┐
│ Method / Parameter │ Arguments / Types │ Description / Primary Use Case │
├──────────────────────────────┼──────────────────────────────┼─────────────────────────────────────────────────────────┤
│ context.storage_state() │ path: Optional[str] │ Captures cookies + localStorage. Returns dict or file. │
│ browser.new_context() │ storage_state: str / Dict │ Initializes context with pre-authenticated session. │
│ context.add_cookies() │ cookies: List[Dict] │ Injects specific cookie objects into active context. │
│ context.cookies() │ urls: Optional[List[str]] │ Returns all active cookies matching URLs or all cookies.│
│ context.clear_cookies() │ None │ Purges all cookies from active context immediately. │
│ context.clear_permissions() │ None │ Clears granted permissions (geolocation, camera, etc.). │
│ context.set_geolocation() │ geolocation: {"latitude":...}│ Emulates physical GPS coordinates for the session. │
├──────────────────────────────┴──────────────────────────────┴─────────────────────────────────────────────────────────┤
│ STORAGE STATE JSON STRUCTURE KEYS: │
│ * "cookies" ──► List[Cookie]: [{name, value, domain, path, expires, httpOnly, secure, sameSite}] │
│ * "origins" ──► List[Origin]: [{origin: "https://...", localStorage: [{name, value}]}] │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘