Playwright 10 ๐ญ Authentication Reuse โ Saving and Loading storageState
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
| Step | Code |
|---|---|
| Navigate | page.goto("/login") |
| Fill | page.getByLabel("Email").fill(...) |
| Submit | page.getByRole("button").click() |
| Wait | page.waitForURL("/dashboard") |
| Save | context.storageState({ path }) |
Config
| Option | Purpose |
|---|---|
testMatch on setup | Restrict to setup files |
dependencies: ["setup"] | Run setup first |
use.storageState | Load the state file |
File and Secret Hygiene
| Item | Rule |
|---|---|
| State file path | playwright/.auth/ |
| Gitignore | playwright/.auth/ |
| Credentials | Environment variables |
| Session expiry | Re-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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Empty auth file | Saved before login completed | Wait for the authenticated page |
| Tests run unauthenticated | dependencies missing | Add dependencies: ["setup"] |
| Session expires mid-suite | Short token lifetime | Re-run setup or use a longer token |
| IndexedDB session not restored | Not in storageState | Use 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
| Item | Value |
|---|---|
| Save state | context.storageState({ path }) |
| Load state | use: { storageState } |
| Run setup first | dependencies: ["setup"] |
| Wait for login | page.waitForURL + assertion |
| Credentials | Environment variables |
| Gitignore | playwright/.auth/ |
| Multiple roles | One 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.storageStatepoints at the file, anddependencies: ["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
dependenciesdoes, 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.
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!