Advanced — Storage state

Learn how to implement a setup step and reuse browser state.

But wouldn't it also be great if we could log in the user once and then reuse the browser state (cookies, localstorage) in other test cases?

You bet! This is where project configuration and the storageState method come in handy!

Write the current browser state to disk

Whenever you perform actions in your Playwright scripts you can write the current state to disk.

await page.context().storageState({ path: authFile });

If you write the state to disk, it should look like this.

{
  "cookies": [
    {
      "name": "name",
      "value": "stefan",
      "domain": "next-example-store-stefan-judis.vercel.app",
      "path": "/",
      "expires": -1,
      "httpOnly": false,
      "secure": false,
      "sameSite": "Lax"
    }
  ],
  "origins": []
}

That's pretty sweet! But now there's the questions, how and when should your read this?

Read the browser state in your test files

Luckily, you only have to pass it to your test or project config.

test.use({ storageState: "./tests/03-04.auth.json" });

test.describe(/* ... */);

Alternatively, you could also define that an entire project in your playwright.config uses the same state.

export default defineConfig({
  // projects that leverage setup and storage state
  // npx playwright test --project=storageState
  projects: [
    {
      name: "setup",
      testMatch: "*.setup.ts",
    },
    {
      // run the `setup` tests before these
      dependencies: ["setup"],
      name: "storageState",
      use: { storageState: "auth.json" },
      testMatch: "*.with-state.spec.ts",
    },
  ],
});
Todo

Solution

💡 If you're stuck, find a working example on GitHub.