#Logging in once with a setup project
AddedMost 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:
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"],
},
],
});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 });
});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();
});
});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)- The config has two projects.
setupmatches only files ending in.setup.ts.chromiumloadsplaywright/.auth/rohit.jsoninto every context and listsdependencies: ["setup"], so Playwright runs the wholesetupproject first, and only startschromiumif setup passed. auth.setup.tssigns in through the form once, waits for "Signed in as rohit" (proof the shop has writtenshop-userto 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.- The output shows the order:
[setup] › tests/auth.setup.ts › sign in as rohitfirst, then the three[chromium]tests. Four runs in total, though only one of them typed a password. - The first two tests open
/practice/shopdirectly 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. 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.- 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
globalSetupfunction lacks (it also ignores config options such asheadless).
After that run, playwright/.auth/rohit.json is a real file in the project. A tiny script prints it:
import { readFileSync } from "node:fs";
console.log(readFileSync("playwright/.auth/rohit.json", "utf8"));{
"cookies": [],
"origins": [
{
"origin": "https://rohit-playwright.pages.dev",
"localStorage": [
{
"name": "shop-user",
"value": "{\"username\":\"rohit\",\"name\":\"Rohit\"}"
}
]
}
]
}cookiesis empty: the shop sets none. A real app's session cookie would be here, with its domain, path, expiry andhttpOnlyflag (the cookie example under "Cookies, localStorage and sessions" shows one).originshas one entry for the shop's origin, with its localStorage:shop-userholds{"username":"rohit","name":"Rohit"}, exactly what the shop wrote when sign-in succeeded. That one value is "being signed in" for this app.- 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.gitignorealready lists it (Chapter 2); if yours doesn't, the docs' fix isecho $'\nplaywright/.auth' >> .gitignore.