QA Interview Hub · Knowledge base · Quizzes · Українська

Playwright

Authentication and storageState

Authentication: storageState and a setup project

Log in once in a setup project and save the context state to a file with storageState. The other projects declare the setup in dependencies and create their contexts from that file, so every test starts signed in. Wait for a visible result of the login before saving, otherwise the file holds an empty session. sessionStorage is not saved, and the file itself goes into .gitignore.

Playwright · Authentication

Two hundred tests, and each one starts with the login form. Can you sign in once for the whole run?

A suite has two hundred tests, and each one opens /login in beforeEach, types a password and waits for the home page. If a login takes four seconds, that is almost fourteen minutes of total time. And when the login form breaks, the whole suite turns red, although it was not the thing under test. This lesson is about how to sign in once, save the state to a file and run the rest of the tests with it already applied, and why a separate setup project is convenient for it.

How it works and why. Authentication in a browser is not magic, it is data: cookies with a session id, sometimes a token in localStorage. All of it lives in a browser context, and a context in Playwright is isolated and cheap. So it is enough to log one context in, "photograph" its data and create new contexts from that snapshot. The snapshot is called storageState and sits in a plain JSON file:

{
  "cookies": [
    { "name": "session", "value": "…", "domain": "app.test", "path": "/",
      "expires": 1790000000, "httpOnly": true, "secure": true, "sameSite": "Lax" }
  ],
  "origins": [
    { "origin": "https://app.test", "localStorage": [{ "name": "token", "value": "…" }] }
  ]
}
WhatIn the snapshot?
Cookies, including httpOnlyyes: Playwright reads them at the context level, not through the page's JavaScript
localStorage for each originyes
IndexedDBonly on request: storageState({ indexedDB: true }) (since version 1.51)
sessionStorageno: it belongs to a tab, not to a context

Who logs the context in, and when? That is what a setup project is for: a separate config project with its own tests that runs first, while the other projects list it in dependencies. That makes the login an ordinary test, with fixtures, retries, a trace and a line in the report.

From login to tests

setup: log in once playwright/.auth/user.json chromium firefox webkit every test starts already logged in setup failed: the dependentprojects do not run at all
Figure 1. The login happens once and the result sits in a file. The arrows show the dependency: the projects do not start until setup has finished.

Example: from a login in every test to a single sign-in. The original version: each test goes through the form itself.

// before: the login repeats before every test
test.beforeEach(async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel('Email').fill(process.env.USER_EMAIL!);
  await page.getByLabel('Password').fill(process.env.USER_PASSWORD!);
  await page.getByRole('button', { name: 'Sign in' }).click();
});

After: one test in the setup project signs in, and the config says that the other projects depend on it and take the state file.

// playwright.config.ts
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'],
    },
  ],
});

The setup file tests/auth.setup.ts: what each line does

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

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

1setup(
  'authenticate',
  async ({ page }) => {
    await page.goto('/login');
    await page
      .getByLabel('Email')
      .fill(
        process.env.USER_EMAIL!,
      );
    await page
      .getByLabel('Password')
      .fill(
        process.env.USER_PASSWORD!,
      );
2    await page
      .getByRole('button', {
        name: 'Sign in',
      })
      .click();
3    await expect(
      page.getByRole('link', {
        name: 'Profile',
      }),
    ).toBeVisible();
4    await page
      .context()
      .storageState({
        path: authFile,
      });
  },
);
  1. setup: This is a test of the setup project, found by testMatch in the config. It runs once, before the projects that depend on it.
  2. Login: The login form is walked through once, not before every test.
  3. Wait: A visible result of the login: until the cookies are set, saving the state is too early.
  4. Save: Cookies and localStorage go into a file that all dependent tests read afterwards.
Figure 2. The numbers lead to the explanations of the code lines.

The storageState option in use applies at the moment the context is created, so a test gets a page with cookies and localStorage already restored, and there is no login step in it. test.use({ storageState }) in a file or describe does the same. The playwright/.auth folder goes into .gitignore: the file holds live credentials.

How to tell the state was saved too early. A typical symptom: setup is green, yet all dependent tests open on the login page. Open the file: if it holds { "cookies": [], "origins": [] }, the snapshot was taken before the server set the session. The click on "Sign in" returns control at once, and the response arrives later. That is why storageState() is always preceded by waiting for a visible result of the login (the "Profile" link in the example) or page.waitForURL. A wait, not a pause: server response time varies.

Limits and alternatives.

  • Expiry. A file saved yesterday may hold an expired session. So on CI the setup runs every time, while locally the file can be reused as long as it is valid.
  • A shared session. All workers share one user. If a test clicks "Sign out", the server may invalidate the session for everyone holding it, and neighbouring tests get logged out. Tests that change account data or end the session need a separate user (see the lesson on API login).
  • A config with several browsers. The state file is the same for all, because it is data, not a binding to a browser. Still, sessions tied to the User-Agent or IP may need a separate login per browser.
  • Other tools. In Cypress a similar role is played by cy.session(), which caches and restores a session between tests. In Selenium you build such a snapshot by hand: save the driver's cookies and add them to a new session.

Common mistakes.

  • Saving the state right after clicking "Sign in": the file has no session cookie, and the rest of the tests fail logged out.
  • Committing the state file: working tokens end up in the repository.
  • A too broad testMatch: the setup file is picked up as an ordinary test in several projects and logs in an extra time.
  • Assuming sessionStorage was saved too: an application that keeps its session there is logged out after the state is restored.
  • Relying on yesterday's file in CI: the session has expired, and the reason for the 401 is not obvious.

Check yourself

The setup test is green, but all dependent tests open on the login page. The cookies array in user.json is empty. Which line of setup holds the cause and what should be added?

Answer

The cause is storageState({ path }) called right after the "Sign in" click: the server has not set the session yet. Before saving, wait for a visible result of the login, for example await expect(page.getByRole('link', { name: 'Profile' })).toBeVisible() or page.waitForURL.

The application keeps a token in sessionStorage. After storageState is restored, a test opens logged out. Why, and how do you work around it?

Answer

sessionStorage belongs to a tab and does not end up in the context snapshot. You read the values in setup through page.evaluate, save them to a separate file and restore them through context.addInitScript before the page's scripts run.

Why is a failing setup project better than a failing login in beforeEach?

Answer

One test fails, with a trace and a clear place of the error, and the dependent projects do not run. With beforeEach all two hundred tests would fail with the same cause, and the report would drown in identical errors.

In an interview. Junior: I log in once in a setup project, save storageState to a file and attach it in the projects through dependencies, so I do not go through the form in every test. The state file goes into .gitignore. Middle/Senior: Setup has a trace, retries and a line in the report, unlike globalSetup, and when it fails the dependent projects simply do not start. Before saving I wait for a visible result of the login, otherwise the file holds an empty session. I remember the limits: sessionStorage is not in the file, a session can expire, and one user for all workers breaks on tests that change the account.

Login through the API in a setup project

In a setup project the session is obtained with a direct request to the login API and saved with request.storageState(). A token in localStorage needs more: it is written on a page of the app before the state is saved. When tests change account data, one shared user causes flaky failures in parallel, so use one user per worker. API login does not test the login form.

Playwright · Authentication

Logging in through the form in setup takes seconds and sometimes fails on an animation. Can you get a session without a browser?

The login form is already covered by separate tests, and going through it again in setup checks nothing new, but adds seconds and fragility: a selector, an animation, a cookie banner. If the application has a login API, the session can be obtained with a direct request. This lesson is about how to do that for a cookie session and for a token in localStorage, and what breaks when all parallel workers share one user.

How it works and why. The login form is just one way to send the server an "email, password" pair. The server replies with a Set-Cookie header or a body with a token, and the browser simply stores it. The request context (request) has a cookie store too and, on receiving Set-Cookie, keeps it the way a browser does. So request.storageState() produces a file in the same format as context.storageState(), and tests pick it up with no difference.

Two ways to get a session

Typical

Login through the UI

A browser starts, a page renders, a form is filled. It depends on selectors, animations and banners. Needed when the form itself is what is being tested.

Better

Login through the API

One POST with no rendering. Faster and more stable, while the login form gets its own tests. Does not fit when sign-in goes through SSO or 2FA without a test bypass.

Figure 1. Setup only prepares the session. Checking the login form itself stays a separate set of tests.

Example 1: a cookie session. If the application keeps its session in cookies, the request fixture is enough:

// auth.setup.ts
import { test as setup, expect } from '@playwright/test';

setup('admin login', async ({ request }) => {
  const res = await request.post('/api/auth/login', {
    data: { email: process.env.ADMIN_EMAIL, password: process.env.ADMIN_PASSWORD },
  });
  await expect(res).toBeOK();
  await request.storageState({ path: 'playwright/.auth/admin.json' });
});

The relative path works thanks to baseURL in the config. The cookie from the response lands in the request context, and request.storageState() saves it to a file.

Example 2: a token in localStorage. Here the API login alone is not enough, because the browser never received the token. It has to be written into localStorage of the right origin, and a browser page is needed only as a container for that origin:

setup('login with a token in localStorage', async ({ page, request }) => {
  const res = await request.post('/api/auth/login', {
    data: { email: process.env.USER_EMAIL, password: process.env.USER_PASSWORD },
  });
  await expect(res).toBeOK();
  const { token } = await res.json();

  await page.goto('/'); // the app's origin is needed to write into its localStorage
  await page.evaluate((t) => localStorage.setItem('token', t), token);
  await page.context().storageState({ path: 'playwright/.auth/user.json' });
});

There is also a variant without a page: write the state file yourself, in the format from the schema in the first lesson, with the app's origin and a token pair in origins. It is faster, but then the format is your responsibility: after a Playwright upgrade it is worth checking.

Example 3: one user for all workers breaks tests. A shared state file means one user for all parallel workers. While tests only read data, there is no problem. But suppose one test tops up a balance and another checks the cart total: alone they pass, together they sometimes fail because of someone else's changes. Such flaky tests do not reproduce in a single thread, and that is the main sign of a shared account.

One account or an account per worker

Typical

One file for all workers

Workers 0, 1 and 2 act as one user: they change the same balance, cart and settings. A test may see someone else's data and fail. A sign-out in one worker may log the others out on the server.

Better

An account per worker

Worker 0 works as user0, worker 1 as user1. The data does not overlap and failures reproduce. The price: the users must be created beforehand.

Figure 2. If tests change account state, isolation comes from a separate user per worker.

Implementation: a worker fixture logs in a user by parallelIndex and caches the state in a file with that index.

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

export const test = base.extend<{}, { workerStorageState: string }>({
  // every test in a worker starts with the state of "its own" user
  storageState: ({ workerStorageState }, use) => use(workerStorageState),

  workerStorageState: [
    async ({ browser }, use) => {
      const id = test.info().parallelIndex;
      const file = path.resolve(test.info().project.outputDir, '.auth/' + id + '.json');
      if (!fs.existsSync(file)) {
        const ctx = await browser.newContext({ storageState: undefined });
        const res = await ctx.request.post('/api/auth/login', {
          data: { email: 'user' + id + '@test.app', password: process.env.USER_PASSWORD },
        });
        expect(res.ok()).toBeTruthy();
        await ctx.storageState({ path: file });
        await ctx.close();
      }
      await use(file);
    },
    { scope: 'worker' },
  ],
});

The users user0…userN must exist beforehand (created by seeding) or be created by this same fixture through the API. There must be at least as many as workers. Why storageState: undefined in newContext: a context created by hand inherits the settings from use, so without an explicit reset it would start with the project's state.

Token lifetime. If the session lives 15 minutes and a run takes 40, the tests at the end will start failing with 401, although everything was green at the start. The ways out: increase the TTL on the test environment, log in again in a fixture when needed, or write short tests with their own API login.

Limits. An API login does not check the login form, so it does not replace its tests. It is possible only when there is a stable login endpoint; for SSO and 2FA you usually need a test bypass on the environment's side, or a UI login once. It also ties the tests to the endpoint's contract: changing its format breaks setup.

Common mistakes.

  • An API login for an application with a token in localStorage without writing the token to a page: the state is saved but empty, and tests are logged out.
  • The user's password in code or in a file in the repository instead of environment variables.
  • One shared account for tests that change data: they pass alone and fail in parallel.
  • Fewer test users than workers: two workers share an account, and the flaky tests come back.
  • Ignoring the TTL: a long run ends with a wave of 401s.

Check yourself

After an API login, an application that keeps its token in localStorage opens logged out, although the state file is not empty. What was missed?

Answer

The file holds only the cookies from the response, while the browser never received the token, so it is not in localStorage. You need to open the application's page, write the token through page.evaluate and only then save the context state (or put the token into the file's origins).

Tests pass with --workers=1 and sometimes fail with four workers. All of them use admin.json. What is the hypothesis and what do you check first?

Answer

The hypothesis: parallel tests change shared data of one account. Check whether the failing tests read data that other tests write to this user's state (balance, cart, settings). The cure: a user per worker through parallelIndex, or data of its own for each test.

In an interview. Junior: In a setup project I can log in through the API and save storageState: it is faster and more stable than the form. If the application keeps its token in localStorage, I add it through page.evaluate. Middle/Senior: When tests change account data, a shared state file produces flaky tests only in parallel, so I make a user per worker with a worker fixture and parallelIndex. Separately I compare the session TTL with the run length and leave the login form to its own tests, because an API login does not check it.

Several roles and the logged-out state

Each role gets its own state file, and two users in one test live in two separate contexts, each with its own storageState. Contexts in one browser are isolated, so the cookies and localStorage of one role are invisible to the other. A guest is checked with an empty state. Session isolation does not isolate data, so every test creates its own entities and closes the contexts it created.

Playwright · Authentication

A client submits an application, an admin approves it. How do you hold two users in one test without mixing sessions?

A real application has a client, a manager, an administrator. Most tests need one role, but the most interesting scenarios involve two: a client submitted an application, an administrator approved it, the client saw the new status. Switching the user in the middle of a test through sign-out and sign-in again is slow and breaks the state of both. This lesson is about how to give each role its own session, how to put two users in one test, and how to check the unauthenticated state.

How it works and why. One role is one state file, and a state file acts at the context level. Contexts in one browser are fully isolated: one cannot see the other's cookies and localStorage. So two users at the same time means two contexts, each with its own storageState. That they work in one browser does not matter: it is the same as two different profiles.

Two roles in one test

one browser adminPageadmin.json clientPageclient.json cookies do not mix one backend: the admin's approvalshows to the client after reload
Figure 1. Isolated sessions, a shared backend: the roles are connected by state on the server, just like two real users.

One role per file or project. If a file checks only one role, test.use at the start of the file or describe is enough:

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

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

test('the administrator sees the list of requests', async ({ page }) => {
  await page.goto('/admin/requests');
  await expect(page.getByRole('heading', { name: 'Requests' })).toBeVisible();
});

A role can also be assigned to a project in the config: an admin project with its own state file and testMatch: /.*\.admin\.spec\.ts/, a client project with another. Then the role is determined by the test file name, and the report groups results by role.

Example: from switching the user to two contexts. The original version: one context, sign-out and sign-in in the middle of the test.

// before: the test goes through the form three times and holds one context
await loginAs(page, 'client');
await page.getByRole('button', { name: 'Submit request' }).click();
await logout(page);
await loginAs(page, 'admin');
await approveFirstRequest(page);
await logout(page);
await loginAs(page, 'client');   // one more login just to see the status

Three passes through the form, and if a sign-out ends the session on the server, there is also a risk of affecting another user. After: two fixtures, each with its own context.

import { test as base, type Page } from '@playwright/test';

type Roles = { adminPage: Page; clientPage: Page };

export const test = base.extend<Roles>({
  adminPage: async ({ browser }, use) => {
    const ctx = await browser.newContext({ storageState: 'playwright/.auth/admin.json' });
    await use(await ctx.newPage());
    await ctx.close();
  },
  clientPage: async ({ browser }, use) => {
    const ctx = await browser.newContext({ storageState: 'playwright/.auth/client.json' });
    await use(await ctx.newPage());
    await ctx.close();
  },
});
test('the administrator approves a client request', async ({ adminPage, clientPage }) => {
  await clientPage.goto('/loans/new');
  await clientPage.getByRole('button', { name: 'Submit request' }).click();

  await adminPage.goto('/admin/requests');
  await adminPage.getByRole('row').first().getByRole('button', { name: 'Approve' }).click();

  await clientPage.reload();
  await expect(clientPage.getByText('Approved')).toBeVisible();
});

A fixture creates its context only when a test asks for it and closes it after use. The order in the test stays natural: the actions of two people alternate, as in life. Note row.first(): in a shared environment the "first row" may be someone else's application, so it is more reliable to look for the row by data created by this test.

The logged-out state. The opposite situation: the project has a shared state configured, but you need to check a guest (a redirect to login, public pages). Then the state is reset with an empty snapshot:

test.describe('guest', () => {
  test.use({ storageState: { cookies: [], origins: [] } });

  test('a protected page redirects to login', async ({ page }) => {
    await page.goto('/account');
    await expect(page).toHaveURL(/login/);
  });
});

The same rule applies to your own contexts: browser.newContext() inherits the settings from use, including the project's storageState. To get a clean context, pass storageState: undefined.

SessionStorage. It does not end up in the snapshot. If the application keeps the session there, it is read in setup through page.evaluate(() => JSON.stringify(sessionStorage)), saved to a separate file and restored through context.addInitScript, which runs before the page's scripts. In the script it is worth checking window.location.hostname, so the values do not leak to third-party domains (for example, to an SSO page).

Limits. Two contexts give session isolation, but not data isolation: if the roles act in a shared environment, tests must still create their own entities. The role state files have to be prepared beforehand, usually by several setup tests. Each role adds a file and a login, so a role used by a single test is often simpler to create right in the fixture. In Cypress the analogue would be cy.session per role, but two users at once in one test are not an option there: Cypress drives a single tab and a single browser, so roles are switched one after another.

Common mistakes.

  • One context and switching the user through sign-out and sign-in in the middle of a test: slow, and the state of both roles gets spoiled.
  • A role baked into the state file while the test expects another: the error shows up as "element not found" rather than as a permissions problem.
  • A forgotten ctx.close() in your own fixtures: contexts pile up, and traces and videos are not finalised.
  • Resetting the state for a guest in one test only, while the neighbouring one expects a guest under the global state.
  • Approving the "first row" in a shared table: the test acts on someone else's data.

Check yourself

The project sets a user's storageState, and the test "a guest is redirected to login" opens the profile instead of login. What is wrong and how do you fix it?

Answer

The project's state applies to all tests, so the "guest" is actually logged in. Reset it in the describe or file: test.use({ storageState: { cookies: [], origins: [] } }).

Why does the clientPage fixture close the context after await use(...) instead of handing out the page and forgetting about it?

Answer

A context created by hand does not close itself. Without ctx.close() contexts pile up, and the traces and videos of these contexts are not finalised. The code after use runs after the test, so cleanup happens even when the test failed.

Why, in a two-role test, do admin and client not see each other's cookies although it is one browser?

Answer

The cookie and localStorage store belongs to a context, not to the browser. Each fixture creates its own context with a separate snapshot, so the sessions are isolated, like two different profiles.

In an interview. Junior: For scenarios with two roles I create two contexts, each with its own storageState, for example the fixtures adminPage and clientPage. For guest tests I reset the state with an empty storageState. Middle/Senior: Contexts isolate sessions but not data, so each test creates its own entities and does not rely on the "first row" of a shared table. I split roles of separate files by projects through testMatch, and I restore sessionStorage, which is not in the file, through addInitScript. I close my own contexts in the fixture so that traces finish.

globalSetup or a setup project: a comparison

globalSetup runs outside the test system, while a setup project is made of ordinary tests with fixtures, retries, trace and a row in the report. So a browser login and anything that should leave a trace belongs in a setup project, and globalSetup is kept for preparation without a browser: migrations, seeding, starting a container. Setup runs on every run and every shard, so it must be fast.

Playwright · Authentication

globalSetup or a setup project? Both "run before the tests", so what is the difference?

A login inside globalSetup through your own chromium.launch() works until it fails. Then the run ends with an error at the start: no report, no trace, no screenshot, and it is unclear whether the form changed or the server is down. This lesson is about how globalSetup differs from a setup project, what each can do and when to pick which: a common interview question.

How it works and why. globalSetup is a function in a separate file that runs once before the whole run, before workers and fixtures. It exists outside the test system: Playwright simply calls it and waits. A setup project, on the contrary, is made of ordinary tests: they go through the same fixtures, retries, trace and report. That is the whole difference: the first mechanism is good for what needs no test infrastructure, and the second gives that infrastructure for free.

Order of execution

1 globalSetupmigrations, seeding, environment check 2 setup projectlogin and storageState; trace and report 3 dependent projectsthe tests, with the saved state 4 teardown projectcleanup, visible in the report too 5 end of globalSetupthe function it returned
Figure 1. globalSetup brackets the whole run, while the login and the cleanup live inside it as tests.
CapabilityglobalSetupsetup project
Visible in the HTML reportnoyes
Trace and screenshotsonly manuallyas in ordinary tests
The page, request fixturesnoyes
Retriesnoyes
Running part of itnothrough dependencies
Way to pass data to testsprocess.env, filesfiles, storageState

Example: from a login in globalSetup to a setup project. The original version: the login inside globalSetup through its own browser.

// before: global-setup.ts
import { chromium, type FullConfig } from '@playwright/test';

export default async function globalSetup(config: FullConfig) {
  const { baseURL } = config.projects[0].use;
  const browser = await chromium.launch();
  const page = await browser.newPage({ baseURL });
  await page.goto('/login');
  await page.getByLabel('Email').fill(process.env.USER_EMAIL!);
  await page.getByLabel('Password').fill(process.env.USER_PASSWORD!);
  await page.getByRole('button', { name: 'Sign in' }).click();
  await page.context().storageState({ path: 'playwright/.auth/user.json' });
  await browser.close();
}

There are several problems at once. An error on any line stops the run before the tests, with no trace and no line in the report, only the exception text is left. There is no wait for the result of the login, so the state is easy to save empty, and the browser stays open if something throws. Such a function does not use project settings (viewport, locale, proxy), and it has no retries. After: the same thing as an ordinary test in a setup project, plus cleanup in a separate teardown project.

The setup and cleanup projects: what each line does

projects: [
  {
1    name: 'setup',
    testMatch: /global\.setup\.ts/,
    teardown: 'cleanup',
  },
  {
2    name: 'cleanup',
    testMatch:
      /global\.teardown\.ts/,
  },
  {
3    name: 'e2e',
    dependencies: ['setup'],
    use: {
      storageState:
        'playwright/.auth/user.json',
    },
  },
],
  1. setup: The login project. The teardown field names the project that runs after all projects that depend on it.
  2. cleanup: The cleanup project: its test removes the data created by the run.
  3. e2e: Depends on setup, so it starts after the login and takes the saved state from the file.
Figure 2. The numbers lead to the explanations of the code lines.
// global.setup.ts
import { test as setup, expect } from '@playwright/test';

setup('login', async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel('Email').fill(process.env.USER_EMAIL!);
  await page.getByLabel('Password').fill(process.env.USER_PASSWORD!);
  await page.getByRole('button', { name: 'Sign in' }).click();
  await expect(page.getByRole('link', { name: 'Profile' })).toBeVisible();
  await page.context().storageState({ path: 'playwright/.auth/user.json' });
});
// global.teardown.ts
import { test as teardown } from '@playwright/test';

teardown('delete test data', async ({ request }) => {
  const res = await request.delete('/api/test-data');
  if (!res.ok()) throw new Error('Could not clean up the data: ' + res.status());
});

Now a login failure shows up as a red test with a screenshot and a trace, and a cleanup that failed does not get lost. The teardown property in the setup project names the project that runs after all the projects depending on it have finished.

What stays with globalSetup. Everything that needs no browser and is required before the tests even get fixtures: DB migrations, seeding, starting a container, checking that the environment is available. The function receives the config and can pass values through process.env, because workers start after it. If it returns another function, that becomes the teardown and runs after all the tests:

// global-setup.ts
import type { FullConfig } from '@playwright/test';
import { runMigrations, seedDatabase, dropSeed } from './db-helpers';

export default async function globalSetup(config: FullConfig) {
  await runMigrations(process.env.DATABASE_URL!);
  process.env.SEED_ID = await seedDatabase();

  return async () => {
    await dropSeed(process.env.SEED_ID!);
  };
}

The path to the file is set by the globalSetup option in the config. A separate globalTeardown option exists too, but the returned function is more convenient: it sees the same variables.

How they behave under filters. If you run a test with a filter, for example npx playwright test checkout, the setup project still runs, because it is in dependencies: Playwright adds the dependencies of the selected project. The --no-deps flag skips them when the state is already saved and you need to quickly repeat one test. A setup failure blocks the dependent projects, and that is right: there is no point running hundreds of tests without a login.

A rule of choice. If a step needs a browser, a request context, or should leave a trace in the report, it is a setup project. If it prepares infrastructure before the tests themselves (migrations, a container, an availability check), it is globalSetup. In large suites both live together: globalSetup prepares the environment, and a setup project logs users in on it.

Limits. A setup project runs on every launch, so it must be fast, otherwise its cost multiplies by the number of shards (each shard runs its own setup). The data setup creates is not necessarily available to the neighbouring machine in CI: the state in a file sits only on the one where setup ran. In Cypress these roles are played by setupNodeEvents and cy.session, and in Selenium frameworks the preparation is usually done in test runner fixtures.

Common mistakes.

  • Logging in inside globalSetup through your own chromium.launch(): there is no trace, and a login error looks like "it just failed".
  • Cleanup in each file's afterAll instead of one teardown: extra requests and races between workers.
  • Making --no-deps a habit: the state goes stale, and a test fails with 401 for no obvious reason.
  • Putting a long seeding into setup: every shard pays for it.
  • Passing data out of globalSetup through an in-memory variable: workers start as separate processes and see only process.env or files.

Check yourself

A run ended with an error mentioning globalSetup right at the start, and the report is empty. What does it say about the choice of mechanism and what should be reworked?

Answer

The error was thrown outside the test system, so there is no trace and no line in the report. If it is a login in a browser, move it to a setup project and leave only browser-free preparation (migrations, seeding) in globalSetup.

Why does npx playwright test checkout still run the login, although there is only one test?

Answer

The project with the test depends on the setup project through dependencies, and Playwright runs the dependencies of the selected project. You can skip them with the --no-deps flag if the state file is still valid.

What is the teardown property in a setup project for, and how is it better than afterAll in every file?

Answer

It runs the cleanup project once, after all projects that depend on setup have finished. afterAll in every file gives extra requests and races between workers, while a teardown project is also visible in the report.

In an interview. Junior: A setup project is better for login, because it has a trace, retries, fixtures and shows up in the report, and cleanup is done through the teardown property. I leave globalSetup for preparation without a browser, such as migrations and seeding. Middle/Senior: The difference is that globalSetup runs outside the test system, so its failure shows up only as text at the start. That is why I make the login, and anything that should leave a trace, into tests. I use --no-deps only when I know the state is still valid, and I count the setup cost per shard on CI.