Save and Reuse Login State in Playwright Python (storage_state)

Logging in through the UI before every test is slow and adds a point of failure to tests that are not about login. Playwright can save the browser’s logged-in state to a file once and load it into every new test context in milliseconds. In this lesson you will save and reuse login state with storage_state, see exactly what the file contains, discover the case where it does not work (session storage), build a pytest session fixture that logs in once per run, handle several user roles, refresh stale state, keep it working with pytest-xdist, and keep the file out of Git.

Advertisement

📖 What You’ll Learn: why reusing login saves time, what a storage state contains (cookies, localStorage, optional IndexedDB), context.storage_state(path=…), new_context(storage_state=…), set_storage_state, why sessionStorage logins are not saved and how to handle them, a session-scoped login fixture with browser_context_args, per-role state files, refreshing expired state, xdist-safe files with worker_id and a lock, and keeping auth files secret.


⏱️ Why Reuse Login?

A UI login takes 2 to 5 seconds. In a suite of 300 tests that need a logged-in user, that is 10 to 25 minutes spent typing the same username and password, and every one of those logins can fail for reasons unrelated to the test.

The fix: log in once, save the browser state, and start every test already logged in. Only your dedicated login tests go through the login form.

Approach Logins per run (300 tests) Isolation
UI login in every test 300 Full
Shared page across tests 1 None: tests leak into each other
Saved storage state 1 Full: every test gets a fresh context with the saved state

📦 What Is Storage State?

When a website logs you in, it remembers you in the browser, usually in cookies or localStorage. context.storage_state() takes a snapshot of both as JSON. Let’s log in to the SQA Shop with “Keep me logged in” ticked and save the state:

📄 save_state.py

import json

from playwright.sync_api import expect, sync_playwright

SHOP = "https://sqatools.in/dummy-ecommerce-website/"

with sync_playwright() as p:
    browser = p.chromium.launch()
    context = browser.new_context()
    page = context.new_page()
    page.goto(SHOP + "#/login")
    page.get_by_test_id("login-username").fill("testuser")
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_test_id("remember-me").check()                 # store the login in localStorage
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")

    context.storage_state(path=".auth/shopper.json")           # folders are created automatically
    browser.close()

state = json.load(open(".auth/shopper.json"))
print("cookies:", len(state["cookies"]))
for origin in state["origins"]:
    print(origin["origin"], "->", [(item["name"], item["value"]) for item in origin["localStorage"] if item["name"].startswith("sp")])

⌨️ Terminal

python save_state.py

🖥️ Output

cookies: 6
https://sqatools.in -> [('spUser', '"testuser"')]

The file holds every cookie and, per origin, every localStorage entry. The store remembers the user in localStorage under spUser.

Now load it into a brand-new context:

📄 reuse_state.py

from playwright.sync_api import expect, sync_playwright

SHOP = "https://sqatools.in/dummy-ecommerce-website/"

with sync_playwright() as p:
    browser = p.chromium.launch()
    context = browser.new_context(storage_state=".auth/shopper.json")
    page = context.new_page()
    page.goto(SHOP)
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")
    print("Logged in without typing a password:", page.get_by_test_id("account-button").inner_text().strip())
    browser.close()

⌨️ Terminal

python reuse_state.py

🖥️ Output

Logged in without typing a password: Hi, Test

No login form, no password, and the store greets the user by name.

📌 Note: storage_state() also accepts indexed_db=True (for apps such as Firebase Authentication that keep tokens in IndexedDB), opfs=True (origin private file system) and credentials=True (virtual passkeys) in recent Playwright versions. Turn them on only if your app stores its login there.


⚠️ The Trap: sessionStorage Is Not Saved

Run the same experiment without ticking “Keep me logged in”:

📄 session_only.py

from playwright.sync_api import expect, sync_playwright

SHOP = "https://sqatools.in/dummy-ecommerce-website/"

with sync_playwright() as p:
    browser = p.chromium.launch()
    context = browser.new_context()
    page = context.new_page()
    page.goto(SHOP + "#/login")
    page.get_by_test_id("login-username").fill("testuser")
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_test_id("login-button").click()                # remember-me NOT ticked
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")
    print("sessionStorage spUser:", page.evaluate("sessionStorage.getItem('spUser')"))
    print("localStorage spUser:  ", page.evaluate("localStorage.getItem('spUser')"))
    context.storage_state(path=".auth/session_only.json")

    fresh = browser.new_context(storage_state=".auth/session_only.json").new_page()
    fresh.goto(SHOP)
    print("New context shows:", fresh.get_by_test_id("account-button").inner_text().strip())
    browser.close()

⌨️ Terminal

python session_only.py

🖥️ Output

sessionStorage spUser: "testuser"
localStorage spUser:   None
New context shows: Login

The user was logged in, but the new context shows Login. Without “Keep me logged in”, the store keeps the login in sessionStorage, which lives only as long as the browser tab and is not part of a storage state.

When your application uses sessionStorage, you have two options:

  1. Log in with the option that persists the session (as here), if the product offers one.
  2. Save sessionStorage yourself and restore it with an init script before the page’s own scripts run:

📄 restore_session.py

import json

from playwright.sync_api import expect, sync_playwright

SHOP = "https://sqatools.in/dummy-ecommerce-website/"

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto(SHOP + "#/login")
    page.get_by_test_id("login-username").fill("testuser")
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")
    saved = page.evaluate("JSON.stringify(sessionStorage)")                      # save

    context = browser.new_context()
    context.add_init_script(f"""
        if (location.hostname === 'sqatools.in') {{
            const data = JSON.parse({json.dumps(saved)});
            for (const [k, v] of Object.entries(data)) sessionStorage.setItem(k, v);
        }}""")                                                                   # restore before page scripts
    page2 = context.new_page()
    page2.goto(SHOP)
    print("Restored session shows:", page2.get_by_test_id("account-button").inner_text().strip())
    browser.close()

⌨️ Terminal

python restore_session.py

🖥️ Output

Restored session shows: Hi, Test

add_init_script runs in every page of the context before the site’s own JavaScript, so the app finds the session as if the user had never left.


Advertisement

🧪 Log In Once per Test Run with pytest

In a pytest suite, create the state in a session-scoped fixture and give it to every context through browser_context_args:

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in
markers =
    anonymous: run the test without the saved login

📄 tests/conftest.py

from pathlib import Path

import pytest
from playwright.sync_api import Browser, expect

AUTH_DIR = Path(__file__).parent.parent / ".auth"
SHOP = "/dummy-ecommerce-website/"


@pytest.fixture(scope="session")
def shopper_state(browser: Browser, base_url) -> Path:
    """Log in through the UI once per run and save the state."""
    path = AUTH_DIR / "shopper.json"
    context = browser.new_context(base_url=base_url)
    page = context.new_page()
    page.goto(SHOP + "#/login")
    page.get_by_test_id("login-username").fill("testuser")
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_test_id("remember-me").check()
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")   # fail setup if login breaks
    context.storage_state(path=path)
    context.close()
    return path


@pytest.fixture
def browser_context_args(browser_context_args, request):
    if request.node.get_closest_marker("anonymous"):
        return browser_context_args
    return {**browser_context_args, "storage_state": request.getfixturevalue("shopper_state")}

📄 tests/test_account.py

import pytest
from playwright.sync_api import Page, expect

SHOP = "/dummy-ecommerce-website/"


def test_greeting(page: Page):
    page.goto(SHOP)
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")


def test_my_orders_link(page: Page):
    page.goto(SHOP)
    page.get_by_test_id("account-button").click()
    expect(page.get_by_test_id("menu-orders")).to_be_visible()


def test_checkout_uses_saved_account(page: Page):
    page.goto(SHOP + "#/search/earbuds")
    page.get_by_role("button", name="Add to cart").first.click()
    page.goto(SHOP + "#/checkout")
    expect(page.get_by_test_id("logged-in-note")).to_contain_text("Signed in as Test User")


@pytest.mark.anonymous
def test_guest_sees_login(page: Page):
    page.goto(SHOP)
    expect(page.get_by_test_id("account-button")).to_contain_text("Login")

⌨️ Terminal

pytest -v --durations=5

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 4 items

tests/test_account.py::test_greeting[chromium] PASSED                    [ 25%]
tests/test_account.py::test_my_orders_link[chromium] PASSED              [ 50%]
tests/test_account.py::test_checkout_uses_saved_account[chromium] PASSED [ 75%]
tests/test_account.py::test_guest_sees_login[chromium] PASSED            [100%]

============================= slowest 5 durations =============================
2.22s setup    tests/test_account.py::test_greeting[chromium]
1.60s call     tests/test_account.py::test_checkout_uses_saved_account[chromium]
1.55s call     tests/test_account.py::test_greeting[chromium]
1.54s call     tests/test_account.py::test_my_orders_link[chromium]
1.11s call     tests/test_account.py::test_guest_sees_login[chromium]
============================== 4 passed in 8.56s ==============================

How it works:

  • browser_context_args is normally session-scoped in pytest-playwright. Overriding it as a function-scoped fixture lets it look at each test’s markers, and pytest-playwright reads it for every new context.
  • request.getfixturevalue("shopper_state") triggers the login only when a test needs it, and only once per session.
  • The anonymous marker gives tests such as “guest sees Login” a clean context.
  • --durations=5 shows that only the first test paid for the login (its setup time); the other tests have no login in their setup and spend their time on the test itself.

💡 Tip: Each test still gets its own context loaded from the file. Adding items to the cart in one test does not affect the next one, unlike sharing one page.


Advertisement

👥 Several Roles

Most applications have more than one kind of user (customer, admin, support). Save one file per role and choose per test:

📄 tests/roles/conftest.py

from pathlib import Path

import pytest
from playwright.sync_api import Browser, expect

AUTH_DIR = Path(__file__).parent.parent.parent / ".auth"
USERS = {"shopper": ("testuser", "Test@123")}          # add "admin": (...) etc. for your app


@pytest.fixture(scope="session")
def state_for(browser: Browser, base_url):
    cache: dict[str, Path] = {}

    def _state(role: str) -> Path:
        if role not in cache:
            username, password = USERS[role]
            context = browser.new_context(base_url=base_url)
            page = context.new_page()
            page.goto("/dummy-ecommerce-website/#/login")
            page.get_by_test_id("login-username").fill(username)
            page.get_by_test_id("login-password").fill(password)
            page.get_by_test_id("remember-me").check()
            page.get_by_test_id("login-button").click()
            expect(page.get_by_test_id("account-button")).to_contain_text("Hi,")
            path = AUTH_DIR / f"{role}.json"
            context.storage_state(path=path)
            context.close()
            cache[role] = path
        return cache[role]

    return _state


@pytest.fixture
def page_as(browser: Browser, base_url, state_for):
    contexts = []

    def _page(role: str):
        context = browser.new_context(base_url=base_url, storage_state=state_for(role))
        contexts.append(context)
        return context.new_page()

    yield _page
    for context in contexts:
        context.close()

📄 tests/roles/test_roles.py

import pytest
from playwright.sync_api import expect


@pytest.mark.anonymous
def test_shopper_and_guest_side_by_side(page_as, page):
    shopper = page_as("shopper")
    shopper.goto("/dummy-ecommerce-website/")
    expect(shopper.get_by_test_id("account-button")).to_contain_text("Hi, Test")

    page.goto("/dummy-ecommerce-website/")                     # the normal page: a guest (anonymous marker)
    expect(page.get_by_test_id("account-button")).to_contain_text("Login")

⌨️ Terminal

pytest tests/roles -v

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 1 item

tests/roles/test_roles.py::test_shopper_and_guest_side_by_side[chromium] PASSED [100%]

============================== 1 passed in 5.88s ==============================

page_as("admin") and page_as("shopper") in the same test is how you test interactions between users, for example an admin approving a customer’s request.


♻️ Expiry: Refresh Stale State

Saved sessions expire: cookies have dates and servers end sessions. Two practical rules:

  1. Create state at the start of every run (as the session fixture does). A file from yesterday is a source of mysterious failures.
  2. If you reuse files between runs locally to save time, check their age and log in again when they are old:

📄 state_age.py

import time
from pathlib import Path

MAX_AGE_MINUTES = 30


def is_fresh(path: Path) -> bool:
    return path.exists() and (time.time() - path.stat().st_mtime) < MAX_AGE_MINUTES * 60


print("shopper.json fresh:", is_fresh(Path(".auth/shopper.json")))
print("missing.json fresh:", is_fresh(Path(".auth/missing.json")))

⌨️ Terminal

python state_age.py

🖥️ Output

shopper.json fresh: True
missing.json fresh: False

In the session fixture: if is_fresh(path): return path before logging in.


⚡ Parallel Runs with pytest-xdist

With pytest -n 4, each worker is a separate process with its own session fixtures, so each worker logs in once. That is usually fine (4 logins instead of 300). Two things to get right:

  • Different file per worker, so workers never write the same file at the same time. pytest-xdist provides a worker_id fixture (gw0, gw1 …, or master without xdist):
path = AUTH_DIR / f"shopper-{worker_id}.json"
  • If the application allows only one active session per user, a second login logs out the first worker. Give each worker its own account (testuser1, testuser2 … chosen by worker_id), or log in once with a file lock (filelock library) and share the file read-only.

⌨️ Terminal

pytest tests/test_account.py -n 2 -q

🖥️ Output

bringing up nodes...
bringing up nodes...

....                                                                     [100%]
4 passed in 8.01s

🔒 Keep Auth Files Secret

A storage state file is a logged-in session: anyone with the file is logged in as that user until the session expires.

📄 .gitignore

.auth/
  • Never commit .auth/ and never upload it as a CI artifact.
  • Use dedicated test accounts with minimal permissions.
  • Do not print the file’s contents in logs.

Advertisement

🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Write a short script that logs in to SQA Shop with “Keep me logged in”, saves the state to .auth/user.json, and prints how many localStorage entries were saved for https://sqatools.in.

Show answer
from playwright.sync_api import expect, sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    context = browser.new_context()
    page = context.new_page()
    page.goto("https://sqatools.in/dummy-ecommerce-website/#/login")
    page.get_by_test_id("login-username").fill("testuser")
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_test_id("remember-me").check()
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi,")
    state = context.storage_state(path=".auth/user.json")
    origin = next(o for o in state["origins"] if o["origin"] == "https://sqatools.in")
    print(len(origin["localStorage"]), "localStorage entries")
    browser.close()

storage_state() both writes the file and returns the same data as a dictionary.

Exercise 2: A teammate saved storage state after logging in, but tests that load it still show the login page. List three possible causes.

Show answer

(1) The app keeps the session in sessionStorage, which storage state does not save (as SQA Shop does without “Keep me logged in”). (2) The session expired or was ended on the server (old file, or another login with the same account logged it out). (3) The state was saved before the login finished, for example right after click() without waiting for a logged-in element. Wait with expect(...) before saving.

Exercise 3: Change the browser_context_args override from the lesson so tests marked @pytest.mark.anonymous and tests in the folder tests/login/ start without saved state.

Show answer
@pytest.fixture
def browser_context_args(browser_context_args, request):
    anonymous = request.node.get_closest_marker("anonymous") or "tests/login/" in request.node.nodeid
    if anonymous:
        return browser_context_args
    return {**browser_context_args, "storage_state": request.getfixturevalue("shopper_state")}

A cleaner alternative is a conftest.py in tests/login/ that applies pytestmark = pytest.mark.anonymous-style behaviour by overriding browser_context_args there.

Exercise 4: Switch an existing context from a guest to the saved shopper without creating a new context.

Show answer
context.set_storage_state(".auth/shopper.json")   # clears cookies/storage, then loads the file
page.reload()

set_storage_state (added in recent Playwright versions) replaces everything in the context with the saved state.


🧠 MCQ Quiz: Save and Reuse Login State (storage_state)

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does context.storage_state() save by default?
  2. Why did the SQA Shop login without “Keep me logged in” not survive in a new context?
  3. How do you start a context with a saved state file?
  4. Why is the login fixture scoped to the session?
  5. What does add_init_script do?
  6. With pytest-xdist and four workers, how many times does the session login fixture run?
  7. Which fixture gives the current xdist worker name such as gw0?
  8. Why must .auth/ be in .gitignore?
  9. What should a login setup fixture do before saving the state?
  10. What does context.set_storage_state(path) do?

Want a longer, timed test? Take the Module 8 mock interview (20 MCQs in 20 minutes).


Advertisement

❓ Frequently Asked Questions

🤔 Is storage_state the same as reusing a browser profile?

No. A profile (launch_persistent_context(user_data_dir=...)) is a whole browser directory with history, cache and settings, and only one browser can use it at a time. A storage state is just cookies and storage, loaded into fresh, isolated contexts, which is what tests need.

🤔 Can I create the state through the API instead of the UI?

Yes, if your application issues session cookies or tokens from an API. Use Playwright’s APIRequestContext to log in, then call request_context.storage_state(path=...), which saves the cookies it received (Module 9).

🤔 Does storage_state work with Firefox and WebKit?

Yes. The file format is the same for all engines, so one file can be used in every browser, as long as the cookies’ domains match the site.

🤔 Should my login tests use the saved state?

No. Tests that check the login page itself (errors, lockout, remember-me) must start anonymous. Mark them, as the lesson does with anonymous.

🤔 What about HTTP Basic authentication?

That is not stored in cookies. Pass http_credentials={"username": ..., "password": ...} in browser_context_args instead.


🏁 Summary

  • context.storage_state(path=...) saves cookies and localStorage; new_context(storage_state=...) starts logged in.
  • sessionStorage is not saved: use a persistent login option or restore it with add_init_script.
  • Log in once in a session fixture, assert the login, and add the file to browser_context_args, with an opt-out marker for anonymous tests.
  • Save one file per role, refresh stale files, and use per-worker files (or accounts) with pytest-xdist.
  • Treat .auth/ files as secrets: never commit or upload them.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page