Playwright Authentication
Playwright Authentication
Authentication in Playwright means getting your tests logged in to the app, so they can test the pages behind the login.
You could log in at the start of every test, but that is slow, and every test repeats the same steps.
A better way: log in once, save the browser state to a file, and start every test from that file.
This chapter uses the Login practice page (username student, password w3schools).
How It Works
When you log in, the app stores something in the browser that says who you are.
Most apps use a cookie.
Some use localStorage.
The practice login page keeps the user in localStorage, under the key pw-user.
Playwright can save this with storageState().
The saved file holds the cookies and the localStorage of every site the page visited.
A browser context is like a new, empty browser profile, with its own cookies and storage.
A new browser context can start with the saved state, so the user is logged in from the start.
The Setup Test
Create a file that logs in and saves the state:
Example
tests/auth.setup.js
// @ts-check
import { test as setup, expect } from '@playwright/test';
const authFile = 'playwright/.auth/user.json';
setup('log in', async ({ page }) => {
await page.goto('login.html');
await page.getByLabel('Username').fill('student');
await page.getByLabel('Password').fill('w3schools');
await page.getByRole('button', { name: 'Log in' }).click();
await expect(page.getByTestId('welcome')).toHaveText('Welcome, student!');
await page.context().storageState({ path: authFile });
});
Example Explained
test as setupis the normaltestfunction with another name, so the code is easy to read- The test logs in like a user would
- The
expect()waits until the login is done. Without it, the state could be saved too early page.context().storageState({ path })writes the cookies andlocalStorageto a JSON file
After it runs, the file looks like this:
playwright/.auth/user.json
{
"cookies": [],
"origins": [
{
"origin": "https://www.w3schools.com",
"localStorage": [
{
"name": "pw-user",
"value": "student"
}
]
}
]
}
The Config
Add a setup project that runs the setup file, and make the browser project depend on it:
Example
playwright.config.js
// @ts-check
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
fullyParallel: true,
reporter: 'html',
use: {
baseURL: 'https://www.w3schools.com/playwright/practice/',
trace: 'on-first-retry',
},
projects: [
{ name: 'setup', testMatch: /.*\.setup\.js/ },
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
storageState: 'playwright/.auth/user.json',
},
dependencies: ['setup'],
},
],
});
testMatchmakes thesetupproject run only files ending in.setup.jsdependencies: ['setup']runs the setup project first, before any chromium teststorageStatestarts every chromium test with the saved state
Read more about projects in Browsers and Projects.
Tests Start Logged In
Now the tests do not log in at all:
Example
tests/account.spec.js
// @ts-check
import { test, expect } from '@playwright/test';
test('starts logged in', async ({ page }) => {
await page.goto('login.html');
await expect(page.getByTestId('welcome')).toHaveText('Welcome, student!');
await expect(page.getByRole('heading', { name: 'My account' })).toBeVisible();
});
test('can log out', async ({ page }) => {
await page.goto('login.html');
await page.getByRole('button', { name: 'Log out' }).click();
await expect(page.getByRole('heading', { name: 'Log in' })).toBeVisible();
});
Output:
Running 3 tests using 2 workers
[1/3] [setup] › tests/auth.setup.js:6:1 › log in
[2/3] [chromium] › tests/account.spec.js:10:1 › can log out
[3/3] [chromium] › tests/account.spec.js:4:1 › starts logged in
3 passed (5.0s)
The setup test ran first.
Then both chromium tests opened the login page and found the user already logged in.
The "can log out" test does not affect the other test.
Each test gets its own browser context, filled from the file, so logging out only changes that one context.
Keep the Auth File Out of Git
The saved state file can contain real session cookies or tokens: the values that keep a user logged in.
Anyone who has the file can act as that user, so never commit it.
Add the folder to .gitignore:
.gitignore
playwright/.auth
The setup project creates the file again on every run, so nothing is lost.
Note: Use a test account, not a real person's account.
Read the password from an environment variable (a value you set outside your code), for example process.env.TEST_PASSWORD, instead of writing it in the test.
Multiple Roles
Many apps have different kinds of users, like an admin and a normal user.
Log in as each one in the setup file, and save each state to its own file:
Example
tests/auth.setup.js
setup('log in as admin', async ({ page }) => {
// ... log in as the admin user
await page.context().storageState({ path: 'playwright/.auth/admin.json' });
});
setup('log in as user', async ({ page }) => {
// ... log in as the normal user
await page.context().storageState({ path: 'playwright/.auth/user.json' });
});
Then choose the state in each test file with test.use().
test.use() changes the options for all tests in that file:
Example
tests/admin.spec.js
test.use({ storageState: 'playwright/.auth/admin.json' });
test('admin can see the settings', async ({ page }) => {
// ... this test runs as the admin
});
To test a page as a logged-out visitor, use an empty state:
Example
test.use({ storageState: { cookies: [], origins: [] } });