← Back to Playwright Mastery
Advanced18 min read

Auth & Storage State

Reuse login sessions with storageState and global setup authentication.

storageState Overview

storageState saves cookies and localStorage from authenticated context to JSON file. Subsequent tests load file to skip repetitive UI login—massive speed gain.

Generate once in setup project; dependent projects inherit via use.storageState config.

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

setup("authenticate", async ({ page }) => {
  await page.goto("/login");
  await page.getByLabel("Email").fill(process.env.TEST_USER!);
  await page.getByLabel("Password").fill(process.env.TEST_PASSWORD!);
  await page.getByRole("button", { name: "Sign in" }).click();
  await page.context().storageState({ path: "playwright/.auth/user.json" });
});

Project Dependencies

Setup project runs first; chromium project depends on setup and references saved storageState. Playwright ensures order in CI parallel execution.

Multiple roles: admin.json, member.json with separate setup tests and project entries.

projects: [
  { name: "setup", testMatch: /.*\.setup\.ts/ },
  {
    name: "chromium",
    use: { storageState: "playwright/.auth/user.json" },
    dependencies: ["setup"],
  },
]

API Login Alternative

Request fixture POST to /api/login faster than form. Add cookies to context programmatically before saving storageState.

Hybrid: API token in localStorage via page.evaluate after cookie session established.

const response = await request.post("/api/auth/login", {
  data: { email: "admin@test.com", password: "secret" },
});
await page.context().addCookies(response.headers()["set-cookie"]);

Session Expiry and Refresh

Regenerate storageState when session TTL shorter than suite duration. Run setup per shard or refresh token in fixture beforeEach if API supports.

Detect expired session redirect to login in test and fail with clear message to regenerate auth file.

  • Gitignore playwright/.auth/*.json if tokens sensitive
  • Do not commit production credentials into storageState files
  • Rotate test account passwords without breaking all specs simultaneously

Multi-Origin Auth

Separate storageState per origin if app spans subdomains—configure domain on cookies correctly. SSO flows may need real IdP test tenant or mocked OAuth token endpoint.

Document auth setup in CONTRIBUTING for new engineers running tests locally.

  • Clear storageState in local dev when auth schema changes
  • Validate setup project still passes before debugging dependent failures
  • Use environment-specific auth files: user.staging.json

Get In Touch


Ready to discuss your next project? Drop me a message.