πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Questions
Question 71 of 100
Authentication
Intermediate

What is storage state and how is it managed?

The Answer

Storage state is a JSON snapshot of a browser context's cookies, localStorage, and sessionStorage. It allows you to pre-load authenticated sessions without going through the login UI.

Deep Dive Explanation

Store multiple auth states for different roles: `admin.json`, `editor.json`, `viewer.json`. Test role-based access control by running the same tests with different storage states. Always regenerate storage state files when tokens expire or auth mechanisms change.

example.spec.ts
// Save storage state
await context.storageState({ path: 'auth.json' });

// auth.json structure:
// {
//   "cookies": [...],
//   "origins": [{
//     "origin": "https://app.com",
//     "localStorage": [{ "name": "token", "value": "eyJhbG..." }]
//   }]
// }

// Load in new context
const context = await browser.newContext({
  storageState: 'auth.json'
});

// Or load inline (e.g., from CI secrets)
const context = await browser.newContext({
  storageState: {
    cookies: [],
    origins: [{
      origin: 'https://app.com',
      localStorage: [{ name: 'token', value: process.env.TEST_TOKEN! }]
    }]
  }
});