Playwright + JS · Lesson 28 of 35

0/35 done

Module 28: Authentication & Sessions

28. Global Authentication & Session Reuse with storageState

19 minlesson

Try it yourself

Implement isValidStorageState:

  1. Accept state object containing cookies and origins arrays.
  2. Return true if state.cookies.length > 0 or state.origins.length > 0.

The editor has a worked example. Read it, tweak it, then press Mark as complete.

Save Authentication State (auth.setup.js)

javascript
import { test as setup } from "@playwright/test";

const authFile = "playwright/.auth/user.json";

setup("authenticate user", async ({ page }) => {
  await page.goto("/login");
  await page.getByLabel("Email").fill("tester@targetqa.com");
  await page.getByLabel("Password").fill("Secret123!");
  await page.getByRole("button", { name: "Sign In" }).click();
  await page.waitForURL("**/dashboard");

  // Save session state to disk:
  await page.context().storageState({ path: authFile });
});

Key Takeaways & Walkthrough Summary

Logging in via the UI in every single test wastes valuable time in CI pipelines. Playwright solves this with storageState: you log in once, save cookies and local storage to a file, and reuse that authenticated state across hundreds of tests. Let's speed up our tests!

Part of the Playwright + JS course (Playwright with JavaScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Can I manage multiple roles (Admin vs Viewer) with storageState?

Yes! Create separate setup files (admin.setup.js and viewer.setup.js) saving to distinct JSON files, then configure separate Playwright projects.

Finished reading?

Review the worked example in the editor, then mark the lesson complete.

JavaScript
Skip