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": "…" }] }
]
}
| What | In the snapshot? |
|---|---|
Cookies, including httpOnly | yes: Playwright reads them at the context level, not through the page's JavaScript |
| localStorage for each origin | yes |
| IndexedDB | only on request: storageState({ indexedDB: true }) (since version 1.51) |
| sessionStorage | no: 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
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'],
},
],
});
// tests/auth.setup.ts
import { test as setup, expect } from '@playwright/test';
const authFile = 'playwright/.auth/user.json';
setup('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!);
await page.getByRole('button', { name: 'Sign in' }).click();
// wait for a visible result of the login: saving before the cookies are set is too early
await expect(page.getByRole('link', { name: 'Profile' })).toBeVisible();
await page.context().storageState({ path: authFile });
});
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.
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.