Skip to main content

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:
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

Reuse Authentication State: Authenticate once in a setup project and reuse the state across all tests to significantly improve test execution time.
  • Separate setup from tests: Use dedicated setup projects for authentication
  • Use environment variables: Store credentials securely in .env files
  • 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

Troubleshooting

Authentication state not persisting

Ensure you’re saving the storage state after the page has fully loaded and authentication is complete:

Cookies not being set correctly

Verify the cookie domain and path match your application:
Authentication state is sensitive data. Add *.json files containing authentication state to your .gitignore file.