Playwright provides powerful authentication mechanisms to handle user login flows efficiently. Instead of logging in before every test, you can authenticate once and reuse the authentication state across all tests.
The most efficient way to handle authentication is to save the authentication state (cookies and localStorage) after login and reuse it in subsequent tests.
1
Perform initial login
Create a setup script that logs in and saves the authentication state:
import { test as setup } from '@playwright/test';setup('authenticate', async ({ page }) => { await page.goto('https://github.com/login'); await page.fill('input[name="login"]', process.env.GITHUB_USER); await page.fill('input[name="password"]', process.env.GITHUB_PWD); await page.click('input[type="submit"]'); // Wait for the final URL to ensure successful login await page.waitForURL('https://github.com/'); // Save authentication state await page.context().storageState({ path: 'auth.json' });});
2
Configure tests to use saved state
Update your playwright.config.ts to use the saved authentication state:
import { defineConfig } from '@playwright/test';export default defineConfig({ use: { // Load authentication state before each test storageState: 'auth.json', },});
3
Use authenticated context in tests
All tests will now start with the authenticated state:
import { test, expect } from '@playwright/test';test('create new repository', async ({ page }) => { // Already authenticated - no need to login await page.goto('https://github.com/new'); await expect(page.getByRole('heading', { name: 'Create a new repository' })).toBeVisible();});