Playwright Authentication: Complete Guide to Login, Storage State, Sessions and Multiple Users
If your Playwright test needs to open a page that requires login, you need authentication.
For example, imagine an online shopping website.
A user logs in with:
Email
Password
Verification
Session cookie
After login, the user can open the dashboard, profile, orders and payment pages.
If Playwright performs the same login steps before every test, your test suite becomes slower and harder to maintain.
Playwright provides better ways to handle authentication.
The most important concept is storage state.
In this guide, you will learn Playwright Authentication from beginner to advanced level, including:
What Playwright authentication means
Login testing
Authentication vs authorization
Cookies
Local storage
storageState
Reusing login sessions
Authentication setup projects
API authentication
Worker-based authentication
Multiple user roles
Admin and normal-user testing
Session storage
Authentication security
Common errors
Best practices
CI/CD authentication
Frequently asked questions
What Is Playwright Authentication?
Playwright Authentication is the process of allowing a Playwright test to access an application as a logged-in user.
A simple flow looks like this:
Open application → Login → Create session → Save authentication state → Reuse state in tests
Instead of making every test perform the complete login process, Playwright can save the authenticated browser state and reuse it.
This can make tests faster and keeps the actual test focused on the feature being tested.
Playwright's current authentication guidance recommends saving reusable authentication state and using it to start tests already authenticated.
Authentication vs Authorization
These two words sound similar, but they have different meanings.
Authentication
Authentication answers:
"Who are you?"
Example:
A user enters:
Email: user@example.com
Password: ********
The application verifies the credentials.
Authorization
Authorization answers:
"What are you allowed to do?"
For example:
A normal employee may see:
Dashboard
Profile
Reports
An administrator may see:
Dashboard
Users
Reports
Settings
Delete User
So:
Authentication = identity
Authorization = permissions
A good Playwright test suite should test both when the application requires them.
Why Should You Reuse Authentication?
Consider a test suite containing 100 tests.
If every test performs:
Open login page
Enter username
Enter password
Click Login
Wait for dashboard
you are repeating the same work many times.
There is another problem.
If the login page breaks, many unrelated tests can fail.
For example:
Login test
Dashboard test
Profile test
Orders test
Settings test
Reports test
All could fail because they depend on the same login flow.
A better approach is:
Authenticate once
↓
Save authentication state
↓
Reuse authentication state
↓
Run feature tests
This separates authentication setup from feature testing.
What Is storageState in Playwright?
storageState allows Playwright to save and reuse browser authentication information.
It can contain information such as cookies and local storage data.
Playwright's current API documentation also supports storage state containing additional browser state, including IndexedDB and virtual WebAuthn credentials in appropriate scenarios.
A simple example is:
await page.context().storageState({
path: 'playwright/.auth/user.json'
});
Later, that state can be loaded:
use: {
storageState: 'playwright/.auth/user.json'
}
Now the test can start with the saved authenticated state.
Recommended Authentication Folder
A clean project can look like this:
project/
│
├── tests/
│ ├── auth.setup.ts
│ ├── dashboard.spec.ts
│ ├── profile.spec.ts
│ └── orders.spec.ts
│
├── playwright/
│ └── .auth/
│ └── user.json
│
├── playwright.config.ts
└── package.json
The Playwright documentation recommends keeping authentication state in a dedicated .auth directory and adding it to .gitignore.
Step 1: Create the Authentication Setup
Create:
tests/auth.setup.ts
Example:
import { test as setup, expect } from '@playwright/test';
import path from 'path';
const authFile = path.join(
__dirname,
'../playwright/.auth/user.json'
);
setup('authenticate', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill('test@example.com');
await page.getByLabel('Password').fill('password');
await page.getByRole('button', {
name: 'Login'
}).click();
await expect(page).toHaveURL(/dashboard/);
await page.context().storageState({
path: authFile
});
});
The important idea is simple:
Login once → save the state.
Step 2: Configure the Setup Project
Your configuration can define an authentication setup project.
import {
defineConfig,
devices
} from '@playwright/test';
export default defineConfig({
testDir: './tests',
projects: [
{
name: 'setup',
testMatch: /.*\.setup\.ts/
},
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
storageState:
'playwright/.auth/user.json'
},
dependencies: ['setup']
}
]
});
The dependencies relationship ensures the authentication setup runs before the dependent project.
Playwright's current authentication guide recommends this setup-project pattern for reusable authentication when tests can safely share an account.
Step 3: Write a Test Without Repeating Login
Now your test becomes much cleaner.
import { test, expect } from '@playwright/test';
test('user can open dashboard', async ({ page }) => {
await page.goto('/dashboard');
await expect(page).toHaveURL(/dashboard/);
});
Notice something important.
There is no:
goto('/login')
There is no:
fill(username)
There is no:
fill(password)
The test starts with the authenticated state.
When Should You Use a Shared Account?
A shared authenticated account is useful when tests do not change shared server-side data in conflicting ways.
For example:
View dashboard
View profile
View reports
Check navigation
These tests may safely use the same account.
But suppose your tests perform:
Create customer
Delete customer
Change account settings
Update order
Running these tests simultaneously with one account can cause test interference.
In that situation, worker-specific accounts can be a better approach.
Playwright explicitly recommends different strategies depending on whether tests modify server-side state.
Authentication Per Worker
Playwright can execute tests using multiple worker processes.
Imagine:
Worker 1 → User 1
Worker 2 → User 2
Worker 3 → User 3
Worker 4 → User 4
Each worker can maintain its own authentication state.
This reduces conflicts when tests modify shared application data.
A worker-based approach can use:
test.info().parallelIndex
to identify the worker.
The official Playwright authentication guide documents this pattern for tests that need isolated accounts while running in parallel.
API Authentication with Playwright
Sometimes logging in through the UI is unnecessary.
Suppose the application provides:
POST /api/login
You can authenticate through the API and save the resulting state.
Conceptually:
const context = await request.newContext();
await context.post('/api/login', {
data: {
username: 'test@example.com',
password: 'password'
}
});
await context.storageState({
path: 'playwright/.auth/user.json'
});
Then browser tests can reuse that state.
This can be faster because Playwright does not need to open the login page and interact with every login element.
Playwright's API testing documentation confirms that authentication state can be shared between API request contexts and browser contexts.
Testing Multiple Roles
Many business applications have different roles.
For example:
Admin
Manager
Employee
Customer
Guest
You can create different authentication states:
playwright/.auth/
├── admin.json
├── manager.json
└── user.json
Then a test can use the required state.
test.use({
storageState: 'playwright/.auth/admin.json'
});
Another test can use:
test.use({
storageState: 'playwright/.auth/user.json'
});
This is useful for authorization testing.
Testing Admin and User Together
Sometimes you need two users in one test.
For example:
Admin creates a user
↓
Normal user logs in
↓
Normal user sees the created data
You can create separate browser contexts.
Conceptually:
const adminContext =
await browser.newContext({
storageState: 'playwright/.auth/admin.json'
});
const userContext =
await browser.newContext({
storageState: 'playwright/.auth/user.json'
});
Each context has its own authenticated identity.
Session Storage
Do not confuse:
Cookies
Local Storage
Session Storage
They are different browser storage mechanisms.
Playwright's standard authentication-state workflow handles common persistent authentication state, but session storage needs special handling because it is not automatically persisted in the same way. The official documentation provides an approach using addInitScript() when session storage must be preserved.
Passkey Authentication
Modern applications may use passkeys.
Playwright now provides virtual WebAuthn credentials for testing passkey flows.
The current Playwright API includes credential creation and installation for virtual WebAuthn authentication.
This is useful when your application supports:
Passkeys
WebAuthn
Security keys
Passwordless authentication
Authentication Security: Very Important
Authentication state is sensitive.
A storage-state file can contain information that allows a test session to act as a logged-in user.
Therefore, never commit real authentication state to GitHub.
Add:
playwright/.auth
to:
.gitignore
For example:
playwright/.auth/
Do not store real production credentials inside test code.
Instead use environment variables or secure CI/CD secrets.
Common Playwright Authentication Problems
Problem 1: Tests suddenly become unauthenticated
Possible reasons:
Authentication expired
Cookies changed
Storage state is old
Application changed its login process
Solution:
Regenerate the authentication state.
Problem 2: storageState file does not exist
Check:
playwright/.auth/user.json
Make sure the setup test actually ran.
Problem 3: Authentication works locally but fails in CI
Check:
Environment variables
Application URL
Credentials
Authentication expiration
CI filesystem paths
Browser version
Network access
Problem 4: Parallel tests modify the same account
Use separate accounts per worker when tests change server-side data.
Problem 5: Authentication file is accidentally committed
Immediately remove the sensitive file from version control and rotate the affected credentials or sessions.
Best Practices for Playwright Authentication
Use these rules:
Authenticate once when possible.
Reuse storageState.
Keep authentication setup separate from feature tests.
Use different accounts when parallel tests modify shared data.
Use API authentication when it is faster and appropriate.
Use separate states for different roles.
Keep authentication files out of Git.
Store secrets in environment variables or CI/CD secret stores.
Regenerate expired authentication state.
Test authorization separately from authentication.
Playwright Authentication vs Login in Every Test
A Simple Mental Model
Remember this:
Login
↓
Create authenticated state
↓
Save state
↓
Load state
↓
Start test already logged in
That is the heart of Playwright Authentication.
Frequently Asked Questions
What is Playwright Authentication?
It is the process of testing an application as an authenticated user.
What is storageState in Playwright?
storageState allows Playwright to save and reuse browser authentication state.
Where should authentication state be stored?
A common Playwright pattern is:
playwright/.auth/
and this directory should be excluded from Git.
Can Playwright authenticate using an API?
Yes. Playwright can authenticate through an API request and reuse the resulting storage state in browser tests.
Can Playwright test multiple users?
Yes. Separate authentication states and browser contexts can be used for different users.
Can Playwright test admin and normal users?
Yes. This is especially useful for authorization testing.
Is storageState safe to publish?
No. Authentication state can contain sensitive session information.
Should every Playwright test perform login?
Usually no. Reusing authentication state is generally cleaner and faster when the test conditions allow it.
Final Takeaway
The best Playwright authentication strategy is not simply "log in before every test."
A scalable approach is:
Authenticate → save state → reuse state → isolate accounts when necessary → protect credentials.
Once you understand storageState, setup projects, API authentication, worker authentication and multiple roles, Playwright authentication becomes much easier to design and maintain.
For beginners, remember just one idea:
Log in once when possible, save the authenticated state, and let your actual tests focus on the feature they are supposed to test.

Comments
Post a Comment