Manuals / Playwright with Python / Chapter 28

Part 4 · Advanced Techniques · advanced · ~45 min · Chapter 28 of 61

20. Authentication & Session Reuse

storage_state — saving/reusing login sessions # Log in once, save the resulting session context = browser.new_context() page = context.new_page() page.goto("https://app.example.com/login") page.get_by_label("Username").fill("testuser") page.get_by_label("Password").fill("testpass") page.get_by_role("button", name="Log in").click() context.storage_state(path="auth_state.json") # Reuse the saved ses

Path progress
45%

Step 1 of 2

Overview

storage_state — saving/reusing login sessions context = browser.new_context() page = context.new_page() # Reuse the saved session — no login steps needed context = browser.new_context(storage_state="auth_state.json") page = context.new_page() What it does: Saves the current context's cookies and localStorage to a JSON file (or returns it as a dict if no path given). Types/params: Pointers: Only captures cookies/localStorage — not sessionStorage or IndexedDB, so if an app's auth relies on those, this approach needs adjustment. What it does: Creates a new context pre-loaded with previously saved cookies/localStorage, skipping the need to log in via UI again. Types/params: state from a prior context.storage_state() call Pointers: This is a major speed win across a large suite — logging in via UI once and reusing the state across hundreds of tests versus repeating a slow UI login flow every single test.

  • path (string, optional) — file path to write the state to; if omitted, returns the state as a dict instead
  • storage_state (string path or dict, required for this use case) — the saved
OverviewDrag stickies · tap for tips
Study mapDrag stickies · tap for tipsKeep it shortdrag · tap →Name the waitdrag · tap →Scope locatorsdrag · tap →Trace when stuckdrag · tap →One browser firstdrag · tap →Isolate statedrag · tap →Assert the UIdrag · tap →Retry wiselydrag · tap →Seed datadrag · tap →Close the loopdrag · tap →Keep it shortdrag · tap →Name the waitdrag · tap →Scope locatorsdrag · tap →Trace when stuckdrag · tap →One browser firstdrag · tap →Isolate statedrag · tap →Pathwise hackdrag · tap →Page under testdrag · tap →Multi-browserdrag · tap →Automation pathdrag · tap →Tooling nodedrag · tap →

Try it

Run / study this snippet

page.goto("https://app.example.com/login")
page.get_by_label("Username").fill("testuser")
page.get_by_label("Password").fill("testpass")
page.get_by_role("button", name="Log in").click()
Was this step clear?
Chapter learning outcomes
  • Global setup for auth (login once, reuse everywhere)

Clear these before you leave

Side quest

20. Authentication & Session Reuse deliverable

Apply one idea from “Overview” in a small script or note.