Skip to content

Storage State

storageState captures cookies and localStorage from a browser context to a JSON file, then restores it in later tests — the backbone of fast authenticated Playwright suites.

Saving and Loading State

Call await context.storageState({ path: 'auth.json' }) after login. Reference in config: use: { storageState: 'auth.json' }.

Storage state includes cookies and per-origin localStorage — enough for most session-based and token-in-localStorage apps.

// Save
await page.context().storageState({ path: '.auth/admin.json' });

// Load in config
use: { storageState: '.auth/admin.json' }

// Load in single test
test.use({ storageState: '.auth/user.json' });

Add .auth/ to .gitignore — files contain session tokens.

storageState Formats

{ cookies: [...], origins: [{ origin, localStorage: [...] }] }
// Empty logged-out state:
{ cookies: [], origins: [] }
  • Generated JSON is human-readable for debugging.
  • Refresh when tokens expire — setup project re-runs.
  • Multiple roles = multiple JSON files.
  • Works with API context via request.newContext({ storageState }).

storageState Reference

Operations and tips.

Operation API
Save context.storageState({ path })
Load global config use.storageState
Load per test test.use({ storageState })
Logged out { cookies: [], origins: [] }
Refresh Re-run setup project
Ignore in git .gitignore .auth folder

Setup Project Flow

projects: [
  { name: 'setup', testMatch: /\.setup\.ts/ },
  {
    name: 'e2e',
    dependencies: ['setup'],
    use: { storageState: '.auth/user.json' },
  },
],

Multiple Role Snapshots

Save admin.json and user.json separately. Tests pick the role they need with test.use({ storageState: '...' }) without duplicating login flows.

Common Mistakes

  • Committing auth JSON with live session tokens.
  • Stale storageState causing mysterious 401 in tests.
  • Parallel tests mutating same user profile.
  • Expecting storageState to include sessionStorage (not included by default).

Key Takeaways

  • storageState saves cookies + localStorage to JSON.
  • Setup projects regenerate auth efficiently.
  • Gitignore auth files; use env-based credentials in setup.
  • Empty state forces logged-out tests.

Pro Tip

If your app stores tokens only in sessionStorage, evaluate addInitScript to seed sessionStorage or ask devs for test hook — storageState doesn't capture sessionStorage unless extended.