Back to All Questions
Question 70 of 100
Authentication
Advanced
How do you reuse login sessions across tests?
The Answer
Save the browser's authentication state (cookies + localStorage) to a JSON file after login, then configure tests to load that state. This skips the login UI for every test.
Deep Dive Explanation
This pattern reduces a 50-test suite from doing 50 logins to 1 login. The `dependencies` configuration ensures the setup project runs first. Add `playwright/.auth/` to `.gitignore` to avoid committing credentials.
example.spec.ts
// auth.setup.ts - Run once to save auth state
import { test as setup } from '@playwright/test';
setup('authenticate', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill('admin@example.com');
await page.getByLabel('Password').fill('secret123');
await page.getByRole('button', { name: 'Sign In' }).click();
await page.waitForURL('/dashboard');
// Save session to file
await page.context().storageState({ path: 'playwright/.auth/user.json' });
});
// playwright.config.ts - Use saved state in all tests
export default defineConfig({
projects: [
{ name: 'setup', testMatch: /auth.setup.ts/ },
{
name: 'authenticated tests',
use: { storageState: 'playwright/.auth/user.json' },
dependencies: ['setup'],
},
],
});