| | |

Playwright 10 ๐ŸŽญ Authentication Reuse โ€” Saving and Loading storageState

โฑ๏ธ Estimated read: 10 min | |

Logging in through the UI in every test is slow and redundant. The login flow is one behavior, and testing it once is enough; the rest of the suite needs an authenticated session, not the login sequence. Playwright’s storageState mechanism separates the two: a setup project logs in once, saves the cookies and localStorage to a file, and every test project loads that file to start already authenticated. The pattern is the documented authentication reuse, and it is the difference between a suite that runs in minutes and one that runs in seconds.

This chapter covers the storageState file, the setup project that creates it, the config that makes the test projects depend on it, and the edge cases where the saved state expires or does not apply. The sections that follow walk through the save, the load, and the multi-role variants that store a separate state per role.

Key point: The setup project logs in through the UI, calls context.storageState({ path }) to write the cookies and localStorage, and the test projects load the file with use: { storageState } and dependencies: ["setup"] so the file exists before they run.


a. The setup project that saves the state

The setup project is a test file that runs before the test projects. It uses the test from @playwright/test with a setup alias, navigates to the login page, fills the credentials, waits for the authenticated page, and writes the state to a file. The file is the serialized cookies and localStorage.

// tests/auth.setup.ts
import { test as setup, expect } from "@playwright/test";

const authFile = "playwright/.auth/user.json";

setup("authenticate", async ({ page, context }) => {
  await page.goto("/login");
  await page.getByLabel("Email").fill(process.env.USER_EMAIL!);
  await page.getByLabel("Password").fill(process.env.USER_PASSWORD!);
  await page.getByRole("button", { name: "Sign in" }).click();

  // Wait for the authenticated page before saving
  await page.waitForURL("/dashboard");
  await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();

  await context.storageState({ path: authFile });
});

The waitForURL and the assertion are not optional. The storageState call saves whatever the context has at the moment it runs, and if the login request has not completed, the saved state has no session cookie. Waiting for a page that only the authenticated user can see is the signal that the login succeeded.

The credentials come from environment variables, not from the file. A committed password is a leaked password, and the process.env read is the pattern that keeps the secret out of the repository. The .env file and the CI secret store are where the values live.

The state file path is usually a .auth/ directory that is gitignored. The file contains a live session cookie, and committing it is the same mistake as committing a password.


b. The config that loads the state

The config declares the setup project and the test projects. The test projects list setup in dependencies, which makes Playwright run the setup project first. The use.storageState option points at the file the setup project wrote.

// playwright.config.ts
import { defineConfig, devices } from "@playwright/test";

export default defineConfig({
  projects: [
    {
      name: "setup",
      testMatch: /.*\.setup\.ts/,
    },
    {
      name: "chromium",
      use: {
        ...devices["Desktop Chrome"],
        storageState: "playwright/.auth/user.json",
      },
      dependencies: ["setup"],
    },
    {
      name: "firefox",
      use: {
        ...devices["Desktop Firefox"],
        storageState: "playwright/.auth/user.json",
      },
      dependencies: ["setup"],
    },
  ],
});

The testMatch on the setup project restricts it to the setup files, so the setup file is not run as a regular test. The dependencies array is what makes the ordering explicit; without it, the test projects can start before the setup file has written the state.

The storageState can also be set globally in the top-level use block, which applies it to every project. The per-project form is the pattern when different projects need different statesโ€”a desktop project and a mobile project that log in as different users.

The .gitignore entry is part of the config. The playwright/.auth/ directory is generated, and it should not be committed.


c. Multiple roles and the state expiry

A suite that tests an admin and a regular user needs two state files. The setup file logs in twice, once per role, and writes two files. The test projects that need the admin state point at the admin file, and the projects that need the user state point at the user file.

// tests/auth.setup.ts
import { test as setup } from "@playwright/test";

const userFile = "playwright/.auth/user.json";
const adminFile = "playwright/.auth/admin.json";

setup("authenticate as user", async ({ page, context }) => {
  await page.goto("/login");
  await page.getByLabel("Email").fill("user@example.com");
  await page.getByLabel("Password").fill("user-password");
  await page.getByRole("button", { name: "Sign in" }).click();
  await page.waitForURL("/dashboard");
  await context.storageState({ path: userFile });
});

setup("authenticate as admin", async ({ page, context }) => {
  await page.goto("/login");
  await page.getByLabel("Email").fill("admin@example.com");
  await page.getByLabel("Password").fill("admin-password");
  await page.getByRole("button", { name: "Sign in" }).click();
  await page.waitForURL("/admin");
  await context.storageState({ path: adminFile });
});

The two setup calls run in the same file, and each saves its own state. The config’s test projects point at the file they need.

The state expires when the session expires. A token with a short lifetime produces a test that passes for an hour and then fails with an authentication error. The fix is to re-run the setup project, which is what dependencies does on every run, or to use a token with a lifetime longer than the suite. A test that saves the state once and reuses it across days is a test that will eventually run against an expired session.

The storageState does not include the IndexedDB or the service workers. An application that stores its session in IndexedDB needs a different setupโ€”a script that writes the IndexedDB directly, or a login in every test. The state file covers cookies and localStorage, which is what most session mechanisms use.


Complete Example Session

// ============================================
// PART 1: THE SETUP PROJECT
// ============================================
// tests/auth.setup.ts
import { test as setup, expect } from "@playwright/test";

const authFile = "playwright/.auth/user.json";

setup("authenticate", async ({ page, context }) => {
  await page.goto("/login");
  await page.getByLabel("Email").fill(process.env.USER_EMAIL!);
  await page.getByLabel("Password").fill(process.env.USER_PASSWORD!);
  await page.getByRole("button", { name: "Sign in" }).click();

  await page.waitForURL("/dashboard");
  await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();

  await context.storageState({ path: authFile });
});

// ============================================
// PART 2: THE CONFIG
// ============================================
// playwright.config.ts
import { defineConfig, devices } from "@playwright/test";

export default defineConfig({
  projects: [
    { name: "setup", testMatch: /.*\.setup\.ts/ },
    {
      name: "chromium",
      use: { ...devices["Desktop Chrome"], storageState: "playwright/.auth/user.json" },
      dependencies: ["setup"],
    },
  ],
});

// ============================================
// PART 3: THE TEST (ALREADY AUTHENTICATED)
// ============================================
// tests/dashboard.spec.ts
import { test, expect } from "@playwright/test";

test("dashboard is visible", async ({ page }) => {
  await page.goto("/dashboard"); // no login step
  await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();
});

// ============================================
// PART 4: THE GITIGNORE
// ============================================
// .gitignore
// playwright/.auth/

The parts covered the setup project, the config, the test that starts authenticated, and the gitignore entry.


Quick Reference

Setup Project

StepCode
Navigatepage.goto("/login")
Fillpage.getByLabel("Email").fill(...)
Submitpage.getByRole("button").click()
Waitpage.waitForURL("/dashboard")
Savecontext.storageState({ path })

Config

OptionPurpose
testMatch on setupRestrict to setup files
dependencies: ["setup"]Run setup first
use.storageStateLoad the state file

File and Secret Hygiene

ItemRule
State file pathplaywright/.auth/
Gitignoreplaywright/.auth/
CredentialsEnvironment variables
Session expiryRe-run setup per run

Best Practices

โœ… Do This:

// Wait for the authenticated page before saving
await page.waitForURL("/dashboard");                           // โœ…

// Save to a gitignored directory
await context.storageState({ path: "playwright/.auth/user.json" }); // โœ…

// Use environment variables for credentials
process.env.USER_EMAIL!                                        // โœ…

โŒ Don’t Do This:

// Save immediately after the click
await page.getByRole("button", { name: "Sign in" }).click();
await context.storageState({ path }); // no session yet        // โŒ

// Commit the auth file
git add playwright/.auth/user.json                             // โŒ

// Hard-code credentials
await page.getByLabel("Password").fill("password123");         // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Empty auth fileSaved before login completedWait for the authenticated page
Tests run unauthenticateddependencies missingAdd dependencies: ["setup"]
Session expires mid-suiteShort token lifetimeRe-run setup or use a longer token
IndexedDB session not restoredNot in storageStateUse a different setup

Real-World Examples

1. Save the state

await context.storageState({ path: "playwright/.auth/user.json" });

2. Load the state

use: { storageState: "playwright/.auth/user.json" }

3. Setup project

setup("authenticate", async ({ page, context }) => { ... });

4. Dependencies

dependencies: ["setup"]

5. Wait for the authenticated page

await page.waitForURL("/dashboard");

6. Multiple roles

const adminFile = "playwright/.auth/admin.json";

7. Env credentials

process.env.USER_EMAIL

8. Gitignore

playwright/.auth/

9. Test without login

await page.goto("/dashboard");

10. Check the state file

cat playwright/.auth/user.json

Visual

The Setup and Reuse Flow

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  SETUP PROJECT                                          โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”           โ”‚
โ”‚  โ”‚ goto /login                              โ”‚           โ”‚
โ”‚  โ”‚ fill credentials                         โ”‚           โ”‚
โ”‚  โ”‚ click Sign in                            โ”‚           โ”‚
โ”‚  โ”‚ waitForURL /dashboard                    โ”‚           โ”‚
โ”‚  โ”‚ storageState({ path })                   โ”‚           โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜           โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  playwright/.auth/user.json                             โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  TEST PROJECTS                                          โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”           โ”‚
โ”‚  โ”‚ newContext({ storageState: user.json })  โ”‚           โ”‚
โ”‚  โ”‚ goto /dashboard  โ†’ already logged in     โ”‚           โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜           โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Config Dependency

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  projects: [                                            โ”‚
โ”‚    { name: "setup", testMatch: /.*\.setup\.ts/ },       โ”‚
โ”‚    {                                                    โ”‚
โ”‚      name: "chromium",                                  โ”‚
โ”‚      use: { storageState: "playwright/.auth/user.json" },โ”‚
โ”‚      dependencies: ["setup"],                           โ”‚
โ”‚    },                                                   โ”‚
โ”‚  ]                                                      โ”‚
โ”‚                                                         โ”‚
โ”‚  dependencies makes setup run first.                    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Multiple Roles

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  setup file                                             โ”‚
โ”‚    โ”œโ”€โ”€ authenticate as user โ†’ user.json                  โ”‚
โ”‚    โ””โ”€โ”€ authenticate as admin โ†’ admin.json                โ”‚
โ”‚                                                         โ”‚
โ”‚  config                                                 โ”‚
โ”‚    โ”œโ”€โ”€ user project  โ†’ storageState: user.json           โ”‚
โ”‚    โ””โ”€โ”€ admin project โ†’ storageState: admin.json          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Expiry Problem

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Token lifetime: 1 hour                                 โ”‚
โ”‚                                                         โ”‚
โ”‚  Suite runs at 9:00  โ†’ passes                           โ”‚
โ”‚  Suite runs at 11:00 โ†’ 401, test fails                  โ”‚
โ”‚                                                         โ”‚
โ”‚  Fix: setup runs on every test run (dependencies),      โ”‚
โ”‚  or use a token with a longer lifetime.                 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Save statecontext.storageState({ path })
Load stateuse: { storageState }
Run setup firstdependencies: ["setup"]
Wait for loginpage.waitForURL + assertion
CredentialsEnvironment variables
Gitignoreplaywright/.auth/
Multiple rolesOne state file per role

Key takeaways:

  • The setup project logs in once and saves the state. It navigates to the login, fills the credentials, waits for an authenticated page, and writes the cookies and localStorage to a file. The wait is the part that makes the state valid.
  • The test projects load the file. use.storageState points at the file, and dependencies: ["setup"] makes the setup project run first. Without the dependency, the test projects can start before the file exists.
  • The state file is a secret. It contains a live session cookie, so it belongs in a gitignored directory, and the credentials belong in environment variables, not in the repository.
  • Multiple roles need multiple files. A setup file that logs in as a user and as an admin writes two state files, and the test projects point at the one they need.
  • The state expires when the session expires. A short-lived token produces a test that passes for an hour and then fails. The setup project re-runs on every test run, which is what dependencies does, or the token needs a lifetime longer than the suite.

Remember: The login flow is one behavior, and it should be tested once. Every other test needs a session, not a login. The setup project is the one place where the UI login runs, and the storageState file is how the rest of the suite starts authenticated. Wait for the authenticated page before saving, keep the file out of git, and let the dependency ordering guarantee that the file exists before the tests need it.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!