Most apps require auth. Playwright avoids repeating full UI login in every test by reusing storageState, API token setup, and dedicated setup projects.
Auth Testing Strategies
Reserve UI login tests for the login feature itself. For other specs, authenticate via API and save cookies/localStorage to a file, then load with storageState in config.
Multi-role testing uses separate storageState files: admin.json, user.json, and different projects or tests.
Setup project generates storageState before dependent projects.
API login in setup is faster than UI when endpoints exist.
Never commit storageState with live production tokens.
OAuth may need real IdP test tenant or mocked token endpoint.
Authentication Patterns
Choose strategy by scenario.
Scenario
Approach
Standard login
Setup project + storageState
API token
POST /auth then save storage
Multiple roles
Multiple auth files + projects
Test login UI
Dedicated spec without storageState
JWT in header
extraHTTPHeaders on request fixture
Session expiry
Mock time or short-lived token tests
OAuth and SSO
Third-party OAuth flows are slow and flaky in CI. Prefer test IdP, auth bypass route in dev builds, or inject session cookies via storageState prepared by backend test helper.
globalSetup for One-Time Login
Run authentication once in globalSetup, save storageState, and reference it in config use — every test starts authenticated without per-file setup.
Common Mistakes
UI login in every test — 10x suite runtime.
Committed storageState files with secrets.
Same auth file for tests that mutate user profile concurrently.
Not testing logout/session expiry at all.
Key Takeaways
Reuse auth via storageState and setup projects.
UI login tests focus on login; other specs skip UI auth.
Separate storage files per role.
OAuth needs special test environment handling.
Pro Tip
Name setup files *.setup.ts and testMatch them only in setup project — keeps auth logic out of regular spec discovery.
Continue with Login Testing to build on what you learned here.