28. Global Authentication & Session Reuse with storageState

The Problem with UI Login in Every Test

If a test suite has 100 tests and each login takes 5 seconds, that's 8+ minutes of pure login overhead!

---

Step 1: Save Authentication State (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 });
});

---

Step 2: Configure Dependency in playwright.config.ts

import { 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"],
},
],
});

---

Step 3: Tests Start Already Logged In!

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();
});

Task

  • Implement isValidStorageState:
  • 1. Accept state of type StorageState.
  • 2. Return true if state.cookies has length > 0 or state.origins has length > 0.
πŸ’‘Common doubts
Did you like the problem?
Lesson 28 of 36
TypeScript
Loading code editor…
Next