Playwright NotesRohit’s interview study guide
Chapter 08

Authentication and State

How to sign in once and reuse the session in every test with a setup project and storageState, how to test with several users at once, what a saved state actually holds (cookies, localStorage, and what it leaves out), the page.localStorage API, and how to test the login form itself, including locked accounts and, from the docs, passkeys. Every test was run with Playwright 1.65.1 against the Practice Shop.

5 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#Logging in once with a setup project

Added

Most tests aren't about signing in, but almost all of them need a signed-in user. Signing in through the form in every test (as Chapters 3 and 7 did) costs a second or more each time, and it means a bug in the login page fails every test in the suite, burying the one failure that matters. Sign in once, save the browser's state to a file, and start every test from that file.

Playwright calls the saved state storageState: the context's cookies and each origin's localStorage, as JSON. page.context().storageState({ path }) writes it; the storageState option (in the config's use, or test.use) loads it into every new context before the test starts. The recommended way to produce it is a setup project: a project that runs a *.setup.ts file first, which the real test projects depend on.

The mental model: a wristband at a festival. You queue at the gate once (sign in), get a wristband (the saved state), and from then on you walk straight into any tent (test) by showing it. Each test still gets its own fresh context, so tests stay isolated; they just all start wearing the same wristband.

The Practice Shop keeps the signed-in user in localStorage (shop-user), so storageState captures it:

playwright.config.ts
import { defineConfig, devices } from "@playwright/test";

export default defineConfig({
  testDir: "./tests",
  use: { baseURL: "https://rohit-playwright.pages.dev" },
  projects: [
    { name: "setup", testMatch: /.*\.setup\.ts/ },
    {
      name: "chromium",
      use: { ...devices["Desktop Chrome"], storageState: "playwright/.auth/rohit.json" },
      dependencies: ["setup"],
    },
  ],
});
tests/auth.setup.ts
import { test as setup, expect } from "@playwright/test";

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

setup("sign in as rohit", async ({ page }) => {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  // Wait until signing in has finished and the state is saved in the page.
  await expect(page.getByText("Signed in as rohit")).toBeVisible();

  await page.context().storageState({ path: authFile });
});
tests/shop.spec.ts
import { test, expect } from "@playwright/test";

test("starts signed in on the products page", async ({ page }) => {
  await page.goto("/practice/shop");
  await expect(page.getByText("Signed in as rohit")).toBeVisible();
  await expect(page.getByRole("listitem")).toHaveCount(8);
});

test("can add to the cart straight away", async ({ page }) => {
  await page.goto("/practice/shop");
  await page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" }).click();
  await expect(page.getByRole("link", { name: "Cart (1)" })).toBeVisible();
});

test.describe("signed out", () => {
  test.use({ storageState: { cookies: [], origins: [] } });

  test("the shop sends you to sign in", async ({ page }) => {
    await page.goto("/practice/shop");
    await expect(page).toHaveURL("/practice/?next=%2Fpractice%2Fshop");
    await expect(page.getByRole("heading", { name: "Sign in" })).toBeVisible();
  });
});
npx playwright test
Running 4 tests using 1 worker

  ✓  1 [setup] › tests/auth.setup.ts:5:1 › sign in as rohit (1.1s)
  ✓  2 [chromium] › tests/shop.spec.ts:3:1 › starts signed in on the products page (967ms)
  ✓  3 [chromium] › tests/shop.spec.ts:9:1 › can add to the cart straight away (963ms)
  ✓  4 [chromium] › tests/shop.spec.ts:18:3 › signed out › the shop sends you to sign in (91ms)

  4 passed (4.1s)
What’s happening
  1. The config has two projects. setup matches only files ending in .setup.ts. chromium loads playwright/.auth/rohit.json into every context and lists dependencies: ["setup"], so Playwright runs the whole setup project first, and only starts chromium if setup passed.
  2. auth.setup.ts signs in through the form once, waits for "Signed in as rohit" (proof the shop has written shop-user to localStorage), then saves the context's state to the file. Without that wait, it could save the state a moment before sign-in finished, and every test would start signed out.
  3. The output shows the order: [setup] › tests/auth.setup.ts › sign in as rohit first, then the three [chromium] tests. Four runs in total, though only one of them typed a password.
  4. The first two tests open /practice/shop directly and are already signed in: the header says "Signed in as rohit" and the products load. Each still has its own context, so the mouse added in the second test isn't in anyone else's cart.
  5. test.use({ storageState: { cookies: [], origins: [] } }) gives one group an empty state, for the tests that must start signed out. The shop redirects to the sign-in page with ?next=%2Fpractice%2Fshop (the page you wanted, URL-encoded), which the test checks.
  6. Since setup is a project, it shows in the HTML report, can record a trace and can use fixtures, like any test. The docs call project dependencies "the recommended approach" and list exactly those as what the older globalSetup function lacks (it also ignores config options such as headless).
AdvancedThe saved file, and why it's gitignored

After that run, playwright/.auth/rohit.json is a real file in the project. A tiny script prints it:

show-auth.mjs
import { readFileSync } from "node:fs";

console.log(readFileSync("playwright/.auth/rohit.json", "utf8"));
node show-auth.mjs
{
  "cookies": [],
  "origins": [
    {
      "origin": "https://rohit-playwright.pages.dev",
      "localStorage": [
        {
          "name": "shop-user",
          "value": "{\"username\":\"rohit\",\"name\":\"Rohit\"}"
        }
      ]
    }
  ]
}
What’s happening
  1. cookies is empty: the shop sets none. A real app's session cookie would be here, with its domain, path, expiry and httpOnly flag (the cookie example under "Cookies, localStorage and sessions" shows one).
  2. origins has one entry for the shop's origin, with its localStorage: shop-user holds {"username":"rohit","name":"Rohit"}, exactly what the shop wrote when sign-in succeeded. That one value is "being signed in" for this app.
  3. Anyone with this file is signed in as rohit. For a real app it holds live session tokens, so playwright/.auth/ must never be committed. The generator's .gitignore already lists it (Chapter 2); if yours doesn't, the docs' fix is echo $'\nplaywright/.auth' >> .gitignore.

#Several users and roles

Added

Real apps have roles: an admin approves what a user submitted, a seller sees the buyer's order, two people chat. Two patterns cover it:

  • One role per test file or group: the setup project saves one state file per user, and each file or describe picks one with test.use({ storageState: "playwright/.auth/ana.json" }).
  • Several users in one test: the test opens one context per user with browser.newContext({ storageState: … }). Each context is a separate browser profile, so the users really are separate sessions, side by side.

The mental model: separate incognito windows, one per person. Same browser, but nothing shared: different storage, different session, different cart.

playwright.config.ts
import { defineConfig, devices } from "@playwright/test";

export default defineConfig({
  testDir: "./tests",
  use: { baseURL: "https://rohit-playwright.pages.dev" },
  projects: [
    { name: "setup", testMatch: /.*\.setup\.ts/ },
    {
      name: "chromium",
      use: { ...devices["Desktop Chrome"], storageState: "playwright/.auth/rohit.json" },
      dependencies: ["setup"],
    },
  ],
});
tests/auth.setup.ts
import { test as setup, expect } from "@playwright/test";

for (const user of ["rohit", "ana"]) {
  setup(`sign in as ${user}`, async ({ page }) => {
    await page.goto("/practice/");
    await page.getByLabel("Username").fill(user);
    await page.getByLabel("Password").fill("playwright");
    await page.getByRole("button", { name: "Sign in" }).click();
    await expect(page.getByText(`Signed in as ${user}`)).toBeVisible();
    await page.context().storageState({ path: `playwright/.auth/${user}.json` });
  });
}
tests/two-users.spec.ts
import { test, expect } from "@playwright/test";

test("rohit and ana shop at the same time without seeing each other's carts", async ({ browser }) => {
  const rohitContext = await browser.newContext({ storageState: "playwright/.auth/rohit.json" });
  const anaContext = await browser.newContext({ storageState: "playwright/.auth/ana.json" });
  const rohit = await rohitContext.newPage();
  const ana = await anaContext.newPage();

  await rohit.goto("/practice/shop");
  await ana.goto("/practice/shop");
  await expect(rohit.getByText("Signed in as rohit")).toBeVisible();
  await expect(ana.getByText("Signed in as ana")).toBeVisible();

  await rohit.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" }).click();
  await ana.getByRole("listitem").filter({ hasText: "USB Microphone" }).getByRole("button", { name: "Add to cart" }).click();
  await ana.getByRole("listitem").filter({ hasText: "USB Microphone" }).getByRole("button", { name: "Add to cart" }).click();

  await expect(rohit.getByRole("link", { name: "Cart (1)" })).toBeVisible();
  await expect(ana.getByRole("link", { name: "Cart (2)" })).toBeVisible();

  await rohitContext.close();
  await anaContext.close();
});

test.describe("as ana", () => {
  test.use({ storageState: "playwright/.auth/ana.json" });

  test("ana's checkout is prefilled with her name", async ({ page }) => {
    await page.goto("/practice/shop");
    await page.getByRole("listitem").filter({ hasText: "Compact Keyboard" }).getByRole("button", { name: "Add to cart" }).click();
    await page.goto("/practice/checkout");
    await expect(page.getByLabel("Full name")).toHaveValue("Ana");
  });
});
npx playwright test
Running 4 tests using 1 worker

  ✓  1 [setup] › tests/auth.setup.ts:4:3 › sign in as rohit (1.1s)
  ✓  2 [setup] › tests/auth.setup.ts:4:3 › sign in as ana (992ms)
  ✓  3 [chromium] › tests/two-users.spec.ts:3:1 › rohit and ana shop at the same time without seeing each other's carts (1.2s)
  ✓  4 [chromium] › tests/two-users.spec.ts:28:3 › as ana › ana's checkout is prefilled with her name (954ms)

  4 passed (5.3s)
What’s happening
  1. The setup file loops over the users and makes one setup test per user, each saving its own file: rohit.json and ana.json. The output shows both setup tests running before the chromium tests.
  2. The first test asks for browser (not page) and creates two contexts, each from a different state file, then a page in each. browser.newContext still applies the config's use options such as baseURL, so goto("/practice/shop") works in both.
  3. Each page's header shows its own user, then rohit adds one mouse while ana adds two microphones, interleaved. Rohit's link says "Cart (1)" and ana's "Cart (2)": separate localStorage, separate carts, in the same test at the same moment.
  4. Contexts made by hand are not closed for you (only the fixture's own context is), so the test closes both at the end. Forgetting is harmless for one test and a slow leak across a big suite.
  5. The describe("as ana") group uses the other pattern: test.use swaps the state file, so its page fixture starts signed in as ana and the checkout's "Full name" is "Ana".
  6. In a real app this is how you test interactions: the admin context approves, then the user context sees "Approved". In the Practice Shop everything is in the browser, so the two users can't affect each other; what this test proves is that each context is a fully separate session.
AdvancedOne account per worker

A shared signed-in account is fine while tests only read. When tests change the account (its cart on a server, its address, its settings), parallel tests using the same account trip over each other. The docs' fix is one account per worker: a worker-scoped fixture signs in once per worker, as that worker's own user, and overrides the built-in storageState fixture. The Practice Shop has two usable accounts, so this suite runs with two workers:

playwright.config.ts
import { defineConfig, devices } from "@playwright/test";

export default defineConfig({
  testDir: "./tests",
  fullyParallel: true,
  workers: 2,
  use: { baseURL: "https://rohit-playwright.pages.dev" },
  projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
});
fixtures.ts
import { test as base, expect } from "@playwright/test";
import fs from "node:fs";
import path from "node:path";

const accounts = ["rohit", "ana"]; // one per worker; a real suite would have workers × 1 test users

export const test = base.extend<{ username: string }, { workerStorageState: string }>({
  // Every test uses its worker's state file.
  storageState: ({ workerStorageState }, use) => use(workerStorageState),
  username: async ({}, use) => use(accounts[test.info().parallelIndex]),

  workerStorageState: [async ({ browser }, use) => {
    const id = test.info().parallelIndex;
    const fileName = path.resolve(test.info().project.outputDir, `.auth/${id}.json`);
    if (fs.existsSync(fileName)) return use(fileName);

    // Sign in once for this worker, in a context with no saved state.
    const page = await browser.newPage({ storageState: undefined, baseURL: "https://rohit-playwright.pages.dev" });
    await page.goto("/practice/");
    await page.getByLabel("Username").fill(accounts[id]);
    await page.getByLabel("Password").fill("playwright");
    await page.getByRole("button", { name: "Sign in" }).click();
    await expect(page.getByText(`Signed in as ${accounts[id]}`)).toBeVisible();
    await page.context().storageState({ path: fileName });
    await page.close();
    console.log(`worker ${id} signed in as ${accounts[id]}`);
    await use(fileName);
  }, { scope: "worker" }],
});

export { expect };
tests/account.spec.ts
import { test, expect } from "../fixtures";

for (const n of [1, 2, 3, 4]) {
  test(`test ${n} gets its worker's own account`, async ({ page, username }) => {
    await page.goto("/practice/account");
    await expect(page.getByText(`Signed in as ${username}`)).toBeVisible();
  });
}
npx playwright test
Running 4 tests using 2 workers

worker 1 signed in as ana
worker 0 signed in as rohit
  ✓  2 [chromium] › tests/account.spec.ts:4:3 › test 2 gets its worker's own account (173ms)
  ✓  1 [chromium] › tests/account.spec.ts:4:3 › test 1 gets its worker's own account (179ms)
  ✓  3 [chromium] › tests/account.spec.ts:4:3 › test 3 gets its worker's own account (170ms)
  ✓  4 [chromium] › tests/account.spec.ts:4:3 › test 4 gets its worker's own account (171ms)

  4 passed (1.9s)
What’s happening
  1. storageState is a built-in option fixture, so a custom test can override it: here it returns the worker's own file. Every page in every test then starts from that file.
  2. workerStorageState is worker-scoped. test.info().parallelIndex (0 or 1 with two workers) picks the account, and the file goes in the project's output folder as .auth/0.json or .auth/1.json.
  3. It signs in with browser.newPage({ storageState: undefined, … }): a page without any saved state, or it would try to load the file it's about to create. It passes baseURL explicitly rather than relying on the config's (a worker fixture can't depend on the test-scoped baseURL option).
  4. Each "signed in as" line prints once per worker, not once per test: four tests, two sign-ins. Which tests land on which worker varies between runs, which is fine: each test only checks it's signed in as its worker's user (username comes from the same parallelIndex).
  5. The result: tests that change account state never share an account with a test running at the same moment, and you sign in once per worker instead of once per test.

#Cookies, localStorage and sessions

Added

Where does "being signed in" live? Depends on the app: a cookie (classic server sessions, most frameworks), localStorage (many single-page apps store a token there; the Practice Shop stores its user there), IndexedDB (Firebase Auth, some offline-first apps) or sessionStorage (per tab). storageState captures the first two by default, the third on request, and never the fourth. Knowing which one your app uses is the first step to debugging "my tests start signed out".

The mental model: storageState is a photo of the cookie jar and the localStorage shelf, taken at one moment, for every origin the context visited. It isn't a photo of the whole browser: tabs, sessionStorage, memory and (unless you ask) IndexedDB aren't in it.

Here's a test that signs in, adds to the cart, adds a cookie, and prints the photo:

tests/state.spec.ts
import { test, expect } from "@playwright/test";

test("what storageState holds", async ({ page, context }) => {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" }).click();
  await expect(page.getByRole("link", { name: "Cart (1)" })).toBeVisible();

  // The shop sets no cookies; this one is added only to show what a cookie looks like in the state.
  await context.addCookies([{ name: "consent", value: "yes", domain: "rohit-playwright.pages.dev", path: "/" }]);

  const state = await context.storageState();
  console.log(JSON.stringify(state, null, 2));
});
npx playwright test
Running 1 test using 1 worker

{
  "cookies": [
    {
      "name": "consent",
      "value": "yes",
      "domain": "rohit-playwright.pages.dev",
      "path": "/",
      "expires": -1,
      "httpOnly": false,
      "secure": false,
      "sameSite": "Lax"
    }
  ],
  "origins": [
    {
      "origin": "https://rohit-playwright.pages.dev",
      "localStorage": [
        {
          "name": "shop-user",
          "value": "{\"username\":\"rohit\",\"name\":\"Rohit\"}"
        },
        {
          "name": "shop-cart",
          "value": "[{\"id\":\"ms-01\",\"name\":\"Wireless Mouse\",\"price\":29.5,\"qty\":1}]"
        }
      ]
    }
  ]
}
  ✓  1 [chromium] › tests/state.spec.ts:3:1 › what storageState holds (1.5s)

  1 passed (2.1s)
What’s happening
  1. context.storageState() with no path returns the state as an object instead of writing a file. It's the same JSON the setup project saved.
  2. cookies now holds the one cookie the test added, with every field a browser stores: the domain and path it was set for, expires: -1 (a session cookie, no expiry), httpOnly, secure and sameSite (Lax, the default when none is given). A real session cookie looks the same, usually with httpOnly: true.
  3. origins lists the shop's origin with its localStorage: shop-user (who is signed in) and shop-cart (the mouse, with its price and quantity). The state holds everything in localStorage, not just the login, so a state file saved with a full cart would start every test with that cart.
  4. That last point is a common trap: save the state right after signing in, before the setup does anything else, or every test inherits the extra data.
Advancedpage.localStorage: reading and writing storage (1.61+)

Playwright 1.61 added page.localStorage and page.sessionStorage: an async API for the current origin's storage, with getItem, setItem, removeItem, clear and items(). Before it, you'd write page.evaluate(() => localStorage.getItem("…")). It's useful for checking what the app stored and for seeding state quickly, such as a cart, without clicking through the UI. The page must already be on the origin, because storage belongs to an origin.

tests/local-storage.spec.ts
import { test, expect } from "@playwright/test";

test("seed a cart through localStorage instead of the UI", async ({ page }) => {
  await page.goto("/practice/");
  await page.localStorage.setItem("shop-user", JSON.stringify({ username: "ana", name: "Ana" }));
  await page.localStorage.setItem("shop-cart", JSON.stringify([
    { id: "au-02", name: "USB Microphone", price: 74.99, qty: 2 },
    { id: "dk-01", name: "Standing Desk Mat", price: 39, qty: 1 },
  ]));
  console.log(await page.localStorage.items());

  await page.goto("/practice/cart");

  await expect(page.getByText("Signed in as ana")).toBeVisible();
  await expect(page.getByTestId("cart-total")).toHaveText("$188.98");

  await page.getByRole("button", { name: "Remove Standing Desk Mat" }).click();
  expect(JSON.parse((await page.localStorage.getItem("shop-cart"))!)).toEqual([
    { id: "au-02", name: "USB Microphone", price: 74.99, qty: 2 },
  ]);
});
npx playwright test
Running 1 test using 1 worker

[
  { name: 'shop-user', value: '{"username":"ana","name":"Ana"}' },
  {
    name: 'shop-cart',
    value: '[{"id":"au-02","name":"USB Microphone","price":74.99,"qty":2},{"id":"dk-01","name":"Standing Desk Mat","price":39,"qty":1}]'
  }
]
  ✓  1 [chromium] › tests/local-storage.spec.ts:3:1 › seed a cart through localStorage instead of the UI (157ms)

  1 passed (592ms)
What’s happening
  1. The test first opens the sign-in page, only so the page is on the shop's origin; localStorage is per origin, and a page at about:blank has none to write to.
  2. Two setItem calls write a signed-in user (ana) and a cart, in exactly the format the shop itself uses. items() returns every key as { name, value } pairs, which the log shows.
  3. Opening /practice/cart now finds a signed-in ana and a cart: two microphones and a mat, $74.99 × 2 + $39.00 = $188.98. No form, no clicks, well under a second of arrange.
  4. After removing the mat through the UI, getItem("shop-cart") reads back what the app saved: only the microphones. That's the other use: checking the app's stored state when that state is the behaviour.
  5. The catch: seeding storage means knowing the app's internal format. If the shop renamed shop-cart or changed its shape, this test would silently seed nothing useful. Use it for arrange steps that are slow through the UI, keep one real UI test for the same path, and prefer the app's API on a real backend (Chapter 9).
AdvancedWhat storageState doesn't save: sessionStorage

The shop keeps the order you just placed in sessionStorage (shop-last-order), which the confirmation page reads. sessionStorage lives with a tab, so storageState leaves it out. Here's that proven: place an order, save the state, and open the confirmation in a new context from that state:

tests/session.spec.ts
import { test, expect } from "@playwright/test";

test("sessionStorage isn't part of storageState", async ({ page, browser }) => {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" }).click();
  await page.goto("/practice/checkout");
  await page.getByLabel("Email").fill("rohit@example.com");
  await page.getByLabel("Delivery address").fill("12 Long Street, Toronto");
  await page.getByLabel("I agree to the terms").check();
  await page.getByRole("button", { name: "Place order" }).click();
  await expect(page.getByRole("heading", { name: "Thank you, Rohit!" })).toBeVisible();
  console.log("in this tab:", await page.sessionStorage.getItem("shop-last-order") !== null);

  const state = await page.context().storageState();
  const second = await browser.newContext({ storageState: state });
  const again = await second.newPage();
  await again.goto(page.url());

  await expect(again.getByText("Signed in as rohit")).toBeVisible();
  await expect(again.getByRole("heading", { level: 1 })).toHaveText("Order not found");
  console.log("in the new context:", await again.sessionStorage.getItem("shop-last-order"));
  await second.close();
});
npx playwright test
Running 1 test using 1 worker

in this tab: true
in the new context: null
  ✓  1 [chromium] › tests/session.spec.ts:3:1 › sessionStorage isn't part of storageState (3.1s)

  1 passed (3.6s)
What’s happening
  1. The first half places an order. On the confirmation page, page.sessionStorage.getItem("shop-last-order") (1.61+, the sessionStorage twin of page.localStorage) finds the order: "in this tab: true".
  2. storageState() is passed straight to browser.newContext as an object (it accepts a path or the object itself), and the new page opens the same confirmation URL.
  3. The new context is signed in (localStorage came across: "Signed in as rohit") but the page says "Order not found", and its sessionStorage has no order (null). The order lived only in the first tab's sessionStorage.
  4. If your app keeps its auth token in sessionStorage, a saved state won't sign tests in. The docs' answer is to save it yourself with page.evaluate and put it back with context.addInitScript before the page loads; better still, ask whether the app should keep it there.
  5. IndexedDB is the other gap, but it has an option: storageState({ path, indexedDB: true }) (1.51+) saves it too, which the docs recommend for apps like Firebase Auth that keep tokens there.

#Testing login itself

Added

Once every other test skips the login form, the form needs its own tests, and they're the one place you deliberately sign in through the UI. Treat it like any feature (Chapter 3): the happy path, the rules, the edges, the failures. For a login page that's usually: valid credentials land you on the right page; you're sent back to the page you asked for; wrong credentials and a locked account show the right message and keep you signed out; empty fields are rejected; the button can't be double-submitted; signing out really signs out.

The mental model: the front door gets its own inspection. Everyone else uses the staff entrance (saved state), so nobody would notice if the front door jammed, unless someone tests it.

tests/login.spec.ts
import { test, expect } from "@playwright/test";

test.beforeEach(async ({ page }) => {
  await page.goto("/practice/");
});

test("valid credentials open the shop", async ({ page }) => {
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();

  await expect(page).toHaveURL("/practice/shop");
  await expect(page.getByText("Signed in as rohit")).toBeVisible();
});

test("the button is disabled while signing in", async ({ page }) => {
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();

  await expect(page.getByRole("button", { name: "Signing in…" })).toBeDisabled();
  await expect(page).toHaveURL("/practice/shop");
});

test("signing in returns you to the page you asked for", async ({ page }) => {
  await page.goto("/practice/cart");
  await expect(page).toHaveURL("/practice/?next=%2Fpractice%2Fcart");

  await page.getByLabel("Username").fill("ana");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();

  await expect(page).toHaveURL("/practice/cart");
});

const failures = [
  { name: "a wrong password", user: "rohit", password: "nope", message: "Wrong username or password." },
  { name: "an unknown user", user: "nobody", password: "playwright", message: "Wrong username or password." },
  { name: "a locked account", user: "locked", password: "playwright", message: "This account is locked. Contact support." },
  { name: "an empty form", user: "", password: "", message: "Enter your username and password." },
];
for (const { name, user, password, message } of failures) {
  test(`${name} is rejected`, async ({ page }) => {
    await page.getByLabel("Username").fill(user);
    await page.getByLabel("Password").fill(password);
    await page.getByRole("button", { name: "Sign in" }).click();

    await expect(page.getByRole("alert")).toHaveText(message);
    await expect(page).toHaveURL("/practice/");
    expect(await page.localStorage.getItem("shop-user")).toBeNull();
  });
}

test("logging out signs you out", async ({ page }) => {
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page.getByText("Signed in as rohit")).toBeVisible();

  await page.getByRole("button", { name: "Log out" }).click();

  await expect(page.getByRole("heading", { name: "Sign in" })).toBeVisible();
  await page.goto("/practice/shop");
  await expect(page).toHaveURL(/\/practice\/\?next=/);
});
npx playwright test
Running 8 tests using 1 worker

  ✓  1 [chromium] › tests/login.spec.ts:7:1 › valid credentials open the shop (1.0s)
  ✓  2 [chromium] › tests/login.spec.ts:16:1 › the button is disabled while signing in (988ms)
  ✓  3 [chromium] › tests/login.spec.ts:25:1 › signing in returns you to the page you asked for (1.0s)
  ✓  4 [chromium] › tests/login.spec.ts:43:3 › a wrong password is rejected (1.0s)
  ✓  5 [chromium] › tests/login.spec.ts:43:3 › an unknown user is rejected (958ms)
  ✓  6 [chromium] › tests/login.spec.ts:43:3 › a locked account is rejected (953ms)
  ✓  7 [chromium] › tests/login.spec.ts:43:3 › an empty form is rejected (172ms)
  ✓  8 [chromium] › tests/login.spec.ts:54:1 › logging out signs you out (1.1s)

  8 passed (7.8s)
What’s happening
  1. These tests use the default config, with no saved state, so each starts signed out on the sign-in page (the beforeEach).
  2. The happy path checks the URL and the header. The button test checks that, right after the click, the button reads "Signing in…" and is disabled for the half second the shop takes: that's what stops a double submit.
  3. The redirect test asks for the cart while signed out, is sent to /practice/?next=%2Fpractice%2Fcart, signs in as ana and lands back on the cart. Losing next is a common real bug, and annoying for users who followed a link.
  4. The failures are one table and a loop: four tests from four rows, each named from its row. Each checks the alert text, that the URL hasn't changed, and, with page.localStorage.getItem (1.61+), that no user was stored. The last check matters: a page that shows an error but also signs you in would pass the first two.
  5. Logging out checks both the visible result (the sign-in heading) and the real one: opening a protected page afterwards redirects to sign in again.
  6. Eight tests, about a second each (the empty form fails at once, before the half-second wait), all independent. This is the only file in a suite that should ever type a password into the form.
AdvancedMFA and passkeys

One-time codes (MFA): the usual options are a test environment where test users have MFA turned off, a backdoor the test environment exposes for the code, or generating the code in the test from the user's TOTP secret with an authenticator library. Whichever you choose, do it once, in the setup project, and save the state like any other login. The Practice Shop has no MFA, so nothing here was run.

Passkeys (WebAuthn), 1.61+: Playwright 1.61 added browserContext.credentials, a virtual WebAuthn authenticator for the context. Per the docs, credentials.install() replaces navigator.credentials.create() and navigator.credentials.get() in all current and future pages of the context (call it before the page first touches navigator.credentials), credentials.create(rpId, options?) seeds a passkey (it generates an ECDSA P-256 key pair if you pass only the relying party id), credentials.get({ rpId }) reads back the passkeys it holds, including ones the page registered itself, and credentials.delete(id) removes one. From 1.62, storageState({ credentials: true }) includes the passkeys in the saved state, and loading such a state installs the authenticator automatically.

The Practice Shop has no passkey sign-in, so the code below was not run. It's the shape of a passkey setup for an app that has one, written from the API reference:

TypeScript
// tests/passkey.setup.ts (illustration only: not run, the Practice Shop has no passkeys)
import { test as setup, expect } from "@playwright/test";

setup("register a passkey and save it", async ({ page, context }) => {
  await context.credentials.install();          // before the app calls navigator.credentials
  await page.goto("/account/security");
  await page.getByRole("button", { name: "Add a passkey" }).click();
  await expect(page.getByText("Passkey added")).toBeVisible();

  const [passkey] = await context.credentials.get({ rpId: "example.com" });
  expect(passkey).toBeDefined();
  // 1.62+: save cookies, localStorage and the passkey together.
  await context.storageState({ path: "playwright/.auth/passkey.json", credentials: true });
});
What’s happening
  1. install() comes first, before any page code touches navigator.credentials; from then on the context answers WebAuthn requests itself, with no hardware key or OS prompt.
  2. The app's own "Add a passkey" flow calls navigator.credentials.create(), and the virtual authenticator creates and stores the key.
  3. credentials.get({ rpId }) returns what it holds (id, rpId, user handle, keys, sign count), which proves registration happened.
  4. With credentials: true, the saved state includes the passkey; a test that loads it gets the authenticator installed with that passkey, so "Sign in with a passkey" works without registering again. To test the passkey sign-in screen itself, seed a known credential with credentials.create(...) and install(), then go to the login page.

#Your turn: sessions for the Practice Shop

Added
Your turn: a setup project for ana

Write a config with a setup project that signs in as ana and saves playwright/.auth/ana.json, and a test project that uses it. Then write a test that opens /practice/account directly and checks the "Display name" field shows "Ana", with no sign-in code in the test.

Show answer
playwright.config.ts
import { defineConfig, devices } from "@playwright/test";

export default defineConfig({
  testDir: "./tests",
  use: { baseURL: "https://rohit-playwright.pages.dev" },
  projects: [
    { name: "setup", testMatch: /.*\.setup\.ts/ },
    { name: "chromium", use: { ...devices["Desktop Chrome"], storageState: "playwright/.auth/ana.json" }, dependencies: ["setup"] },
  ],
});
tests/auth.setup.ts
import { test as setup, expect } from "@playwright/test";

setup("sign in as ana", async ({ page }) => {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("ana");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page.getByText("Signed in as ana")).toBeVisible();
  await page.context().storageState({ path: "playwright/.auth/ana.json" });
});
tests/account.spec.ts
import { test, expect } from "@playwright/test";

test("ana's display name defaults to Ana", async ({ page }) => {
  await page.goto("/practice/account");
  await expect(page.getByText("Signed in as ana")).toBeVisible();
  await expect(page.getByLabel("Display name")).toHaveValue("Ana");
});
npx playwright test
Running 2 tests using 1 worker

  ✓  1 [setup] › tests/auth.setup.ts:3:1 › sign in as ana (1.0s)
  ✓  2 [chromium] › tests/account.spec.ts:3:1 › ana's display name defaults to Ana (216ms)

  2 passed (2.3s)
What’s happening
  1. The setup project matches auth.setup.ts, signs in once, waits for the header, and saves the state. The chromium project depends on it and loads the file.
  2. The test opens the account page directly. Without the saved state, the shop would redirect to sign-in; with it, the page loads signed in as ana.
  3. The field's default is the user's name, "Ana". The test checks the header too, so a failure says clearly whether it was the session or the field.
Your turn: seed the cart with page.localStorage

Without clicking any "Add to cart" button, start a test signed in as rohit with three Wireless Mice in the cart, open the cart, press "−" once, and check the quantity is 2 and the total $59.00. Use page.localStorage (1.61+).

Show answer
tests/seed.spec.ts
import { test, expect } from "@playwright/test";

test("a seeded cart can be changed in the UI", async ({ page }) => {
  await page.goto("/practice/");
  await page.localStorage.setItem("shop-user", JSON.stringify({ username: "rohit", name: "Rohit" }));
  await page.localStorage.setItem("shop-cart", JSON.stringify([{ id: "ms-01", name: "Wireless Mouse", price: 29.5, qty: 3 }]));
  await page.goto("/practice/cart");
  await expect(page.getByTestId("cart-total")).toHaveText("$88.50");

  await page.getByRole("button", { name: "Decrease quantity of Wireless Mouse" }).click();

  await expect(page.getByLabel("Quantity of Wireless Mouse", { exact: true })).toHaveText("2");
  await expect(page.getByTestId("cart-total")).toHaveText("$59.00");
});
npx playwright test
Running 1 test using 1 worker

  ✓  1 [chromium] › tests/seed.spec.ts:3:1 › a seeded cart can be changed in the UI (233ms)

  1 passed (779ms)
What’s happening
  1. The first goto puts the page on the shop's origin so it has a localStorage to write to.
  2. Two setItem calls write a signed-in rohit and a cart line with qty: 3, in the shop's own format. The cart page shows $88.50 (3 × $29.50), which proves the seed worked before the test acts.
  3. One click on "Decrease quantity of Wireless Mouse" takes it to 2, and the total to $59.00. exact: true keeps "Quantity of Wireless Mouse" from also matching the two buttons whose names contain it (Chapter 3).
  4. This skips sign-in and four clicks. It's fine for arrange steps, as long as another test covers adding to the cart through the UI.

Written fresh, no doc. Tests were run with @playwright/test 1.65.1 (Chrome for Testing 159, Firefox 159, WebKit 27.2) against the Practice Shop at /practice/; facts come from playwright.dev, read 2026-11-24.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.