Playwright + TS · Lesson 28 of 36
Module 28: Authentication & Sessions
Try it yourself
Implement isValidStorageState:
The editor has a worked example. Read it, tweak it, then press Mark as complete.
In this lesson
If a test suite has 100 tests and each login takes 5 seconds, that's 8+ minutes of pure login overhead!
auth.setup.ts)import { test as setup, expect } from "@playwright/test";
const authFile = "playwright/.auth/user.json";
setup("authenticate user", async ({ page }) => {
await page.goto("https://targetqa.com/login");
await page.getByLabel("Email").fill("tester@targetqa.com");
await page.getByLabel("Password").fill("Password123!");
await page.getByRole("button", { name: "Sign In" }).click();
// Wait until navigated to dashboard
await page.waitForURL("**/dashboard");
// Save cookies and localStorage
await page.context().storageState({ path: authFile });
});playwright.config.tsimport { defineConfig, devices } from "@playwright/test";
export default defineConfig({
projects: [
// Setup project runs first
{ name: "setup", testMatch: /.*\.setup\.ts/ },
// Tests reuse the saved state!
{
name: "chromium",
use: {
...devices["Desktop Chrome"],
storageState: "playwright/.auth/user.json",
},
dependencies: ["setup"],
},
],
});import { test, expect } from "@playwright/test";
test("view billing details", async ({ page }) => {
// Page is ALREADY authenticated! Zero login steps required!
await page.goto("/billing");
await expect(page.getByRole("heading", { name: "Invoices" })).toBeVisible();
});Logging in via the user interface 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 in milliseconds. In this lesson, we will configure global authentication and multi-role testing. Let's speed up our tests!
Part of the Playwright + TS course (Playwright with TypeScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.
Create two setup files: admin.setup.ts saving to admin.json, and viewer.setup.ts saving to viewer.json. Then configure separate Playwright projects using their respective storageState files.
You can override storageState for that single test file using: test.use({ storageState: { cookies: [], origins: [] } });
Finished reading?
Review the worked example in the editor, then mark the lesson complete.