agentleFS
RoninForgeRoninForge/roninforge-playwright/skills/playwright-setup-auth/SKILL.md

playwright-setup-auth

Skill0 starsChanged 7 months agoMITView on GitHub

Set up Playwright authentication via the setup-project + storageState pattern. Covers single shared session (read-only tests), per-worker storage state (mutating tests), multi-role projects (admin/user/guest), and JWT bypass tokens for the fastest deterministic auth.

  • Reads credentials

The file

We split this skill into the rules it gives an agent

1 rule. About 0 are common, 0 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Use when tests create/update/delete data tied to the logged-in user.

    line 80

≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Set up Playwright Authentication

When to Use

When the application under test requires login, and tests beyond a smoke check need an authenticated session. The naive approach is to log in via the UI in beforeEach - this is slow and flaky. Use one of the four patterns below depending on what your tests do.

Decision tree

  • Read-only tests, single user is fine → Pattern 1 (single shared storageState).
  • Tests that mutate user state → Pattern 2 (per-worker storageState).
  • Tests across multiple roles (admin/user/guest) → Pattern 3 (multi-role projects).
  • Want the fastest, most deterministic auth and the app can mint test JWTs → Pattern 4 (JWT bypass).

Pattern 1: Single shared storageState

Step 1: write the setup file

// tests/auth.setup.ts
import { test as setup, expect } from "@playwright/test";
import * as fs from "node:fs";
import * as path from "node:path";

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

setup("authenticate", async ({ page }) => {
  fs.mkdirSync(path.dirname(authFile), { recursive: true });

  await page.goto("/login");
  await page.getByLabel("Email").fill(process.env.E2E_USER!);
  await page.getByLabel("Password").fill(process.env.E2E_PASS!);
  await page.getByRole("button", { name: "Sign in" }).click();

  // Wait for a real post-login indicator BEFORE saving state.
  await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();

  await page.context().storageState({ path: authFile });
});

Step 2: wire into config

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

export default defineConfig({
  projects: [
    { name: "setup", testMatch: /.*\.setup\.ts/ },
    {
      name: "chromium",
      use: {
        ...devices["Desktop Chrome"],
        storageState: "playwright/.auth/user.json",
      },
      dependencies: ["setup"],
    },
  ],
});

Step 3: gitignore the auth dir

# .gitignore
playwright/.auth/

Step 4: set env vars

Local: .env (also gitignored), loaded via dotenv at the top of playwright.config.ts. CI: repo secrets.

Pattern 2: Per-worker storageState

Use when tests create/update/delete data tied to the logged-in user. Sharing one user across workers causes data races.

// tests/fixtures.ts
import { test as base, expect } from "@playwright/test";
import * as fs from "node:fs";
import * as path from "node:path";

type WorkerFixtures = { workerStorageState: string };

export const test = base.extend<{}, WorkerFixtures>({
  // Override the built-in storageState with the worker-scoped one.
  storageState: ({ workerStorageState }, use) => use(workerStorageState),

  workerStorageState: [
    async ({ browser }, use, workerInfo) => {
      const file = path.resolve(
        `playwright/.auth/${workerInfo.workerIndex}.json`,
      );

      if (!fs.existsSync(file)) {
        fs.mkdirSync(path.dirname(file), { recursive: true });
        const ctx = await browser.newContext({ storageState: undefined });
        const page = await ctx.newPage();

        const email = `e2e-worker-${workerInfo.workerIndex}@example.com`;
        const password = process.env.E2E_PASS!;

        await page.goto("/login");
        await page.getByLabel("Email").fill(email);
        await page.getByLabel("Password").fill(password);
        await page.getByRole("button", { name: "Sign in" }).click();
        await expect(
          page.getByRole("heading", { name: "Dashboard" }),
        ).toBeVisible();

        await ctx.storageState({ path: file });
        await ctx.close();
      }

      await use(file);
    },
    { scope: "worker" },
  ],
});

export { expect };

The pre-existing accounts (e2e-worker-0@example.com, e2e-worker-1@example.com, ...) must be seeded in your test database. A migration or a seed script before the test run is the simplest approach.

Pattern 3: Multi-role projects

// tests/auth.setup.ts
import { test as setup, expect } from "@playwright/test";
import * as fs from "node:fs";
import * as path from "node:path";

async function authenticate(
  page: import("@playwright/test").Page,
  email: string,
  password: string,
  postLoginHeading: string,
  file: string,
) {
  fs.mkdirSync(path.dirname(file), { recursive: true });
  await page.goto("/login");
  await page.getByLabel("Email").fill(email);
  await page.getByLabel("Password").fill(password);
  await page.getByRole("button", { name: "Sign in" }).click();
  // Always scope to a known post-login heading. A bare getByRole("heading")
  // matches the /login page's own heading and saves pre-login cookies.
  await expect(page.getByRole("heading", { name: postLoginHeading })).toBeVisible();
  await page.context().storageState({ path: file });
}

setup("authenticate as admin", async ({ page }) => {
  await authenticate(
    page,
    process.env.E2E_ADMIN_USER!,
    process.env.E2E_ADMIN_PASS!,
    "Admin dashboard",
    "playwright/.auth/admin.json",
  );
});

setup("authenticate as user", async ({ page }) => {
  await authenticate(
    page,
    process.env.E2E_USER!,
    process.env.E2E_PASS!,
    "Dashboard",
    "playwright/.auth/user.json",
  );
});
// playwright.config.ts (excerpt)
projects: [
  { name: "setup", testMatch: /.*\.setup\.ts/ },
  {
    name: "chromium-admin",
    testMatch: /.*\.admin\.spec\.ts/,
    use: { ...devices["Desktop Chrome"], storageState: "playwright/.auth/admin.json" },
    dependencies: ["setup"],
  },
  {
    name: "chromium-user",
    testMatch: /.*\.user\.spec\.ts/,
    use: { ...devices["Desktop Chrome"], storageState: "playwright/.auth/user.json" },
    dependencies: ["setup"],
  },
];

For one-off role flips, override per-test instead:

test.use({ storageState: "playwright/.auth/admin.json" });

test("admin can delete users", async ({ page }) => {
  /* ... */
});

Pattern 4: JWT bypass tokens

The fastest auth pattern - no UI, no flake. Requires app cooperation.

App side (Node/TS example)

// In the app, only mounted when E2E_TOKEN_SECRET is set.
if (process.env.E2E_TOKEN_SECRET) {
  app.post("/test/token", (req, res) => {
    if (req.headers["x-e2e-secret"] !== process.env.E2E_TOKEN_SECRET) {
      return res.status(403).end();
    }
    const token = signSessionToken({ sub: req.body.sub, role: req.body.role });
    res.json({ token });
  });
}

Test side

// tests/fixtures.ts
import { test as base, expect, type Page } from "@playwright/test";

type Fixtures = { authedPage: Page };

export const test = base.extend<Fixtures>({
  authedPage: async ({ browser }, use) => {
    const ctx = await browser.newContext();
    const res = await ctx.request.post("/test/token", {
      data: { sub: "alice", role: "admin" },
      headers: { "x-e2e-secret": process.env.E2E_TOKEN_SECRET! },
    });
    const { token } = await res.json();
    await ctx.addCookies([
      {
        name: "session",
        value: token,
        url: process.env.E2E_BASE_URL!,
        httpOnly: true,
        secure: true,
        sameSite: "Lax",
      },
    ]);
    const page = await ctx.newPage();
    await use(page);
    await ctx.close();
  },
});

export { expect };

Constraints:

  • The /test/token endpoint must be gated by an env var that is unset in production.
  • It must refuse without the matching secret header.
  • It must sign with the same key as the real auth flow.

Common mistakes

  • Saving storageState before login completes - file has only the pre-login cookies. Always assert a post-login indicator before saving.
  • Setup project failing silently - dependents are skipped (not failed), and if your reporter only shows non-skipped, you see green CI with no tests run. Always inspect the setup project's report when downstream tests are mass-skipped.
  • Per-worker auth file collision - two workers writing to the same path. Use workerInfo.workerIndex in the file path.
  • storageState: "..." pointing at a non-existent file - tests run unauthenticated. Add dependencies: ["setup"] so the file is guaranteed to exist.
  • Committing playwright/.auth/ - leaks live session cookies. Always gitignore.
  • Logging the password - it ends up in trace.zip and HTML reports. Never console.log(process.env.E2E_PASS).

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.