lecture 8 of 180 completed

Logging in once for the whole suite

storageState saves your login to a file so tests start logged in, without depending on each other.

This one needs a real project: it saves your session to a file on disk, which the editor here has no way to do. It is worth reading anyway, because almost every Playwright suite in a real company uses it.

Logging in through the form takes about three seconds. That sounds small. With eighty tests it is four minutes of every run, spent typing the same password.

You might think: log in once, then let the other tests use that session. Please do not. Your tests would depend on each other, and a single test would fail when run alone.

Playwright solves this properly. You log in once in a setup project, save the browser state to a file, and every test starts from that file with a fresh browser.

First, a setup file that logs in and saves the result:

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

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

setup('authenticate', async ({ page }) => {
  await page.goto('/');
  await page.getByLabel('Email').fill('demo@nimbus.app');
  await page.getByLabel('Password').fill('secure123');
  await page.getByRole('button', { name: 'Sign in' }).click();
  await expect(page.getByTestId('welcome-message')).toBeVisible();

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

storageState writes the cookies and local storage to a file. That file is your saved login.

Then tell your config to run setup first and use that file:

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

Here is the part interviewers like to hear. Each test still gets a brand new browser context, and the saved state is loaded into it. Tests do not share a live session. They share a saved copy. So they stay completely independent and you still save the minutes.

Two practical notes. Add playwright/.auth to your .gitignore, because that file is a real login. And if you need two kinds of user, save two files and create one project per role.

Remember this: save the login to a file, not the order of your tests.

Reference: Authentication.