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.
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.
Continue with JWT Auth Testing to build on what you learned here.