94 / 139 · 13 Browser Automation with Playwright · Fixtures and Test Data← prev⊞ allnext →☰ Read as one page
10.4Authentication State Reuse
Logging in through the UI for every test is slow. Playwright's storageState lets you authenticate once and reuse the session across tests.
// auth.setup.ts — runs once before all tests
import { test as setup } from '@playwright/test';
setup('authenticate', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill('test@example.com');
await page.getByLabel('Password').fill('password');
await page.getByRole('button', { name: 'Sign in' }).click();
await page.waitForURL('/dashboard');
// Save authentication state (cookies + localStorage)
await page.context().storageState({ path: '.auth/user.json' });
});
// playwright.config.ts
export default defineConfig({
projects: [
{ name: 'setup', testMatch: /.*\.setup\.ts/ },
{
name: 'tests',
dependencies: ['setup'],
use: { storageState: '.auth/user.json' },
},
],
});
Now all tests in the tests project start already logged in — no login UI interaction per test.