Overview
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.Authentication Strategies
Storage State API
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:
2
Configure tests to use saved state
Update your
playwright.config.ts to use the saved authentication state:3
Use authenticated context in tests
All tests will now start with the authenticated state:
Manual Cookie Management
For more control, you can manually set cookies in the browser context:Local Storage Setup
Set localStorage items for authentication:Multiple Authentication States
Test scenarios with different user roles by creating multiple authentication states:API Authentication
Authenticate API requests using the request context:Store authentication credentials in environment variables, never commit them to version control.
Best Practices
- Separate setup from tests: Use dedicated setup projects for authentication
- Use environment variables: Store credentials securely in
.envfiles - Test multiple roles: Create separate authentication states for different user roles
- Verify authentication: Always check that authentication succeeded before saving state
- Handle token expiration: Implement logic to refresh tokens when they expire
