Programming

Use Playwright Project Dependencies to Authenticate Once and Reuse Storage State Across Tests

Build a Playwright setup project that signs in once, saves browser storage state, and makes that state available to dependent test projects. Configure the project dependency, write the setup test, and verify a protected page without repeating login steps.

A test suite that signs in separately for every test repeats work that is not necessarily part of what those tests are meant to verify. It can also make unrelated checks depend on the login flow. Playwright’s authentication guidance describes a different pattern: authenticate once in a setup project, save the authentication state, and reuse it to start tests already authenticated.

This tutorial implements that pattern with Playwright Test and TypeScript. A project dependency makes the order explicit: the setup project runs before the test project that depends on it. The setup is still a regular test, so it runs within the test runner rather than as a separate, manually managed browser script.

The sample assumes an application with an email-and-password form and a protected account page. Replace its URL, labels, and success indicator with those in your application. The exact authentication mechanism is application-specific; the objective here is to save the resulting browser storage state after a successful sign-in and configure the consumer project to load it.

Understand the setup and reuse flow

There are two distinct operations: the setup test signs in and writes state; the dependent project uses that state when creating test contexts. This is not one browser page shared by every test. Tests should still navigate to the page and perform the actions relevant to their own assertions.

flowchart LR
    A["Setup project"] --> B["Sign in"]
    B --> C["Save storage state"]
    C --> D["Dependent project"]
    D --> E["Tests use saved state"]

Project dependencies express the ordering between projects. The setup project is named in the consumer project’s dependencies array. Playwright’s documentation recommends project dependencies over globalSetup for this kind of setup: the setup appears in the HTML report, supports traces and fixtures, and participates in standard test-runner configuration.

1. Create a private state-file location

Choose one path for the generated authentication state. This example uses playwright/.auth/user.json. Add its directory to .gitignore:

playwright/.auth/

Treat generated state as sensitive. It can represent an authenticated user, so do not commit a real state file or expose it in a public artifact. Use a disposable test account and credentials supplied by your local environment or CI secret store; do not put a password directly in a test file.

The directory does not have to be named .auth. The important implementation detail is consistency: the setup test must write to the same path that the dependent project configures as its storageState.

2. Define the setup and consumer projects

In playwright.config.ts, create a project that selects only the authentication setup test. Then make the browser project depend on it and configure the saved state file for that project.

import { defineConfig, devices } from '@playwright/test';
import path from 'node:path';

const authFile = path.join(__dirname, 'playwright/.auth/user.json');

export default defineConfig({
  testDir: './tests',
  projects: [
    {
      name: 'setup',
      testMatch: /auth\.setup\.ts/,
    },
    {
      name: 'chromium',
      use: {
        ...devices['Desktop Chrome'],
        storageState: authFile,
      },
      dependencies: ['setup'],
    },
  ],
});

The first project’s testMatch selects auth.setup.ts. The second project’s dependency name must match the first project’s name: here both use setup. A project dependency means the prerequisite project runs before its dependent project. The storageState setting points the consumer project at the file the setup test creates.

If your configuration already has browser projects, apply this pattern to the projects that need the authenticated state. For example, a project can add dependencies: ['setup'] while retaining its existing use settings. Keep an anonymous project separate if some tests need to verify signed-out behavior; do not give it the authenticated state simply because it shares the configuration file.

The setup project uses the normal Playwright Test configuration. That matters when diagnosing problems: the documentation distinguishes dependencies from globalSetup by noting that dependencies can use fixtures and standard runner behavior, and that setup is visible as a separate project in the HTML report.

3. Write a regular setup test

Create tests/auth.setup.ts. Import test as setup to make its role clear. The test opens the login page, submits credentials, confirms that sign-in succeeded, and saves the browser context’s storage state.

import { test as setup, expect } from '@playwright/test';
import fs from 'node:fs';
import path from 'node:path';

const authFile = path.join(__dirname, '../playwright/.auth/user.json');

setup('authenticate', async ({ page }) => {
  const username = process.env.E2E_USERNAME;
  const password = process.env.E2E_PASSWORD;

  if (!username || !password) {
    throw new Error('Set E2E_USERNAME and E2E_PASSWORD before running tests');
  }

  await fs.promises.mkdir(path.dirname(authFile), { recursive: true });

  await page.goto('https://your-app.example.com/login');
  await page.getByLabel('Email').fill(username);
  await page.getByLabel('Password').fill(password);
  await page.getByRole('button', { name: 'Sign in' }).click();

  await expect(
    page.getByRole('heading', { name: 'Dashboard' })
  ).toBeVisible();

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

The directory-creation step makes the example work when the ignored directory does not exist yet. __dirname is used here so the setup test and config can resolve the same project-relative location; if your TypeScript module setup differs, use a path-resolution approach that fits your project and verify both values resolve identically.

Change the form locators to match your page. getByLabel assumes the inputs have associated labels, and getByRole assumes the button and heading expose the accessible names shown. If your application uses a redirect or another post-login marker, assert that instead. The assertion is not decorative: it makes the setup fail at the login step rather than saving state after a form submission that did not actually authenticate.

The code calls page.context().storageState({ path: authFile }) only after that success check. The value of this pattern is not the particular filename or dashboard text; it is the ordering of the operations: complete the login, verify the expected signed-in condition, and then persist state for the consumer project.

4. Keep credentials outside the test source

Set the environment variables before running the suite. In a POSIX shell, for example:

E2E_USERNAME='[email protected]' E2E_PASSWORD='replace-me' npx playwright test

This is a local command example; avoid typing a real production password into shell history. In CI, configure the values using the platform’s secret mechanism. The setup test deliberately throws an error if either value is absent, which gives a direct failure instead of attempting to fill a form with an empty string.

If your login uses another mechanism, adapt the setup’s interaction while preserving the same structure. For instance, a login flow may include an identity-provider redirect or another challenge. The supplied example does not implement those application-specific steps; do not assume that a username/password form is sufficient for every site. Ensure the setup test reaches a stable authenticated condition before saving state.

5. Write a consumer test

Create tests/account.spec.ts. It should test account-page behavior, not repeat the login flow.

import { test, expect } from '@playwright/test';

test('shows the signed-in account', async ({ page }) => {
  await page.goto('https://your-app.example.com/account');

  await expect(
    page.getByRole('heading', { name: 'Account' })
  ).toBeVisible();
  await expect(page.getByText('Signed in')).toBeVisible();
});

The chromium project’s use.storageState setting supplies the saved state when the project runs. The test still uses its own page fixture and navigates to the page it needs. Replace the sample assertions with stable UI behavior from your app; avoid asserting private account details unless the test specifically owns and prepares those details.

This separation makes failures easier to interpret. A failure in auth.setup.ts points toward credentials, login-page behavior, or the success condition. A failure in account.spec.ts after setup passed points toward the protected page or its expected behavior, although authentication state can still be a cause worth checking.

6. Run and inspect the setup project

Run the configured suite with:

npx playwright test

The setup project should run before the dependent project. In the HTML report, look for the setup project separately from the consumer project. Playwright’s documentation says project dependencies are shown in that report and support traces; these features can help you inspect the setup flow when it fails.

Start diagnosis with the setup result rather than assuming that a state file left over from an earlier run proves the current login succeeded. Check, in order:

  1. Are E2E_USERNAME and E2E_PASSWORD present in the process running Playwright?
  2. Does the login URL resolve to the expected environment?
  3. Do the locators match the actual input labels and button name?
  4. Does the post-login assertion identify a successful authenticated state?
  5. Does the setup write to the same path that storageState reads?

If the setup passes but the consumer appears signed out, check that the consumer project actually has storageState: authFile and depends on the project named setup. Also confirm that the saved state represents the authentication mechanism your application uses. A file’s existence alone does not prove that it contains usable state.

What this pattern does not provide

Project dependencies handle setup ordering. They do not make shared server-side data isolated. If several tests use one test account and change the same records, tests can interfere with each other even though they start with saved authentication state. Keep test data predictable and consider whether the scenarios can safely use the same identity and data. Authentication reuse is not a substitute for a strategy for test data.

Nor does the pattern hand every test the setup page or its in-memory JavaScript state. The consumer project uses the saved browser state to initialize tests; a test still needs to navigate and perform any page-specific steps it requires. This is why the account test above opens /account itself instead of relying on the setup test’s current URL.

The saved state can also become unusable if the application’s session is no longer valid. If protected-page assertions begin failing, inspect whether setup ran and succeeded in the current run, and whether the application accepts the resulting state. Do not weaken the protected-page assertion just to make the suite green.

When to choose project dependencies

Playwright documents two ways to configure global setup and teardown: a setup file configured with globalSetup, or project dependencies. Its documentation recommends project dependencies because they integrate with the test runner. The comparison specifically says setup appears as a separate project in the HTML report, traces can be recorded, fixtures are supported, and standard configuration is applied. It contrasts this with globalSetup, which is not shown as a separate project and does not support fixtures or trace recording according to that comparison.

For this authentication workflow, the setup test is a regular test selected by testMatch, and the consumer project lists the setup project in dependencies. This makes both the setup action and the ordering visible in the project configuration. Use globalSetup only if its different lifecycle and reporting behavior better suits your case; it is not necessary to introduce it for the example here.

Troubleshooting checklist

  • The setup test is not selected: confirm it is under testDir and its filename matches /auth\.setup\.ts/.
  • The consumer runs without the setup: verify the consumer’s dependencies contains the exact setup project name.
  • The state file is missing: check the setup test’s resolved path, directory creation, and whether the setup passed before the consumer ran.
  • The file exists but the page is signed out: verify the post-login assertion and the consumer’s storageState path; also check that the saved state is suitable for the application’s authentication flow.
  • Login fails before the assertion: check credentials, environment URL, and locators before changing the consumer test.
  • Tests fail only as a group: investigate shared test-account data and concurrent modifications; project dependencies do not isolate application data.

The core implementation is intentionally small: select a setup test with testMatch, make consumers depend on the setup project, save storage state after verifying sign-in, and configure consumers to load that state. Keep credentials and generated state private, and keep authentication checks in setup so ordinary tests can focus on the behavior they are intended to cover.

External Sources used for this article

Related Articles

View all →