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
| Capability | globalSetup | setup project |
|---|---|---|
| Visible in the HTML report | no | yes |
| Trace and screenshots | only manually | as in ordinary tests |
| The page, request fixtures | no | yes |
| Retries | no | yes |
| Running part of it | no | through dependencies |
| Way to pass data to tests | process.env, files | files, 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.
// playwright.config.ts
projects: [
{ name: 'setup', testMatch: /global\.setup\.ts/, teardown: 'cleanup' },
{ name: 'cleanup', testMatch: /global\.teardown\.ts/ },
{ name: 'e2e', dependencies: ['setup'], use: { storageState: 'playwright/.auth/user.json' } },
],
// 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
globalSetupthrough your ownchromium.launch(): there is no trace, and a login error looks like "it just failed". - Cleanup in each file's
afterAllinstead of one teardown: extra requests and races between workers. - Making
--no-depsa 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.envor 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.
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.