Playwright authentication: sign in once with storageState

8 min read · TypeScript · 6 linked exercises

Most of an app sits behind a sign-in. If every test signs in through the form, the suite is slow, and one problem with the sign-in page fails every test at once.

Playwright's answer is to sign in once, save the browser's session to a file, and start every other test from that file. This guide shows the setup, what the file does and doesn't contain, and the faster route through the API.

Test the sign-in form once

The form itself still needs tests: a wrong password, a correct one, a reload and signing out. Write them once, in one file. No other test should need to use the form.

test('signs in and stays signed in after a reload', async ({ page }) => {
  await page.goto('/auth/sign-in');
  await page.getByLabel('Username').fill('TedBuckland');
  await page.getByLabel('Password').fill('Alligator3');
  await page.getByRole('button', { name: 'Sign in' }).click();

  await expect(page.getByRole('status')).toHaveText('Signed in as TedBuckland');

  await page.reload();
  await expect(page.getByRole('status')).toHaveText('Signed in as TedBuckland');
});
Practise it
  • Sign In & SessionsAdvancedSign in, reload, open a second tab and sign out.
  • Login FormBeginnerEvery path of a login form, including a lockout after failed attempts.

Save the session with storageState

A signed-in browser differs from a signed-out one only by what it stores: cookies and, in many apps, a token in localStorage. context.storageState() writes both to a JSON file. Do it in a setup test:

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

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

setup('sign in', async ({ page }) => {
  await page.goto('/auth/sign-in');
  await page.getByLabel('Username').fill('TedBuckland');
  await page.getByLabel('Password').fill('Alligator3');
  await page.getByLabel('Remember me').check();
  await page.getByRole('button', { name: 'Sign in' }).click();

  // Wait until the app has stored the session, then save it.
  await expect(page.getByRole('status')).toHaveText('Signed in as TedBuckland');

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

The assertion before storageState() matters. Without it the file can be written while the sign-in request is still running, and it holds a signed-out browser.

The file contains a working session, so treat it like a password: add playwright/.auth to .gitignore.

Run it first with a setup project

A setup project runs before the projects that depend on it. In playwright.config.ts:

projects: [
  { name: 'setup', testMatch: /.*\.setup\.ts/ },
  {
    name: 'chromium',
    use: {
      ...devices['Desktop Chrome'],
      storageState: 'playwright/.auth/user.json',
    },
    dependencies: ['setup'],
  },
],

Every test in the chromium project now opens the app already signed in. Each test still gets a new browser context, so tests don't share anything except the starting state.

Tests that need a signed-out browser, such as the sign-in tests themselves, turn the state off for their file or describe block:

test.use({ storageState: { cookies: [], origins: [] } });

Because the setup is an ordinary test, it appears in the HTML report and records a trace when it fails. That's the reason to prefer it over a globalSetup script.

Practise it
  • Sign In & SessionsAdvancedWrite the setup test, then a test that starts from the saved file.

What storageState doesn't save

storageState() saves cookies and localStorage. It doesn't save sessionStorage, which belongs to a single tab and is gone when the tab closes.

That decides whether your setup works. An app that keeps its session in sessionStorage unless the user ticks "Remember me" produces a file with no session in it, and the tests that use the file start at the sign-in form. When a saved state doesn't sign you in, open the JSON file and look for the session before you change any test.

If the app only uses sessionStorage, put the value back yourself before the page loads:

await page.addInitScript((session) => {
  sessionStorage.setItem('session', session);
}, JSON.stringify(savedSession));

The same rule explains new tabs. A second page in the same context shares cookies and localStorage with the first, but it has its own, empty sessionStorage.

Practise it
  • Sign In & SessionsAdvancedSave the state with and without "Remember me" and compare the two files.

Sign in through the API

The form is the slow way in. If the app has a sign-in endpoint, call it with the request fixture and hand the result to the browser. In the Mini Shop the endpoint returns a token and the app reads it from localStorage:

const response = await request.post('/api/shop/login', {
  data: { email: 'alex@example.com', password: 'Password1' },
});
const { token } = await response.json();

// Runs before the page's own scripts, on every navigation.
await page.addInitScript((value) => localStorage.setItem('qa-shop-token', value), token);

await page.goto('/shop/checkout');

When the app uses cookies, the request fixture already holds them after the call, and request.storageState({ path }) saves them in the same format as the browser version.

Tests that never open a browser send the token as a header instead:

const api = await playwright.request.newContext({
  baseURL,
  extraHTTPHeaders: { Authorization: `Bearer ${token}` },
});

const me = await api.get('/api/me');
Practise it
  • Page Objects & FixturesAdvancedWrite a signIn fixture that gets a token from the API.
  • UI + API TogetherAdvancedRegister a new account for each test and sign the browser in with its token.
  • API TestingAdvancedCall a protected endpoint with and without a bearer token.

Several users and roles

Save one file per role in the setup, for example admin.json and user.json, and choose one per file or describe block with test.use({ storageState: 'playwright/.auth/admin.json' }).

A test where two users interact needs two contexts, one per user:

const adminContext = await browser.newContext({ storageState: 'playwright/.auth/admin.json' });
const userContext = await browser.newContext({ storageState: 'playwright/.auth/user.json' });

const adminPage = await adminContext.newPage();
const userPage = await userContext.newPage();

A shared account is shared data. If tests running in parallel all sign in as the same user and change that user's cart or settings, they break each other. Give each parallel worker its own account, or create a new account for each test through the API.

Sign-in in a popup

"Sign in with…" buttons open the provider in a popup window. The popup is a second page: wait for it, fill it in, and return to the first page when it closes.

const popupPromise = page.waitForEvent('popup');
await page.getByRole('button', { name: 'Sign in with Acme ID' }).click();
const popup = await popupPromise;

await popup.getByLabel('Email').fill('ada@example.com');
await popup.getByLabel('Password').fill('secret');
await popup.getByRole('button', { name: 'Allow' }).click();

await expect(page.getByText('Signed in as ada@example.com')).toBeVisible();

Real providers often block automated browsers or ask for a second factor. Don't run your whole suite through them. Test the popup flow against a provider you control, and use a saved state or the API everywhere else.

Practise it
  • Tabs & WindowsAdvancedSign in through a provider popup that closes itself.

Common mistakes

  • Signing in through the form in beforeEach. It works, but it adds the slowest step of the app to every test.
  • Committing the auth file. It holds a live session. Keep it out of the repository.
  • Reusing an old file. Sessions expire. Let the setup project create the file on every run.
  • Passwords in the test code. Read them from environment variables. The CI guide shows how to pass them as secrets.

Exercises in this guide

More guides