Save Login State in Playwright and Reuse It Across Tests
Playwright Test lets you save the browser state after logging in (cookies and localStorage) to a file with storageState, and then start other tests from that state. In E2E tests for member pages and admin screens, you no longer have to type the credentials on the login screen before every test.
In my test environment, I prepared a small app that requires login and compared two approaches: logging in before every test, and logging in once at the start and saving the state. The number of logins the server received went from 3 for three tests to 1. I also include, as they appeared, the errors for a missing saved file and for a session that expired on the server side.
The test environment was Ubuntu 24.04, Node.js 22.23.4, npm 10.9.9, @playwright/test 1.63.0, and TypeScript 5.9.3, using only Chromium. The app was a test app running locally; I did not log in to any real service. I did not test Firefox or WebKit, runs on a CI service, UI mode, logging in by calling an API, using a different account per worker, switching between multiple roles (such as admin and regular user), or logins that use sessionStorage or IndexedDB.
- 1. The login-enabled app used for testing
- 2. Logging in before every test
- 3. Logging in once in a setup project and saving the state
- 4. Contents of the saved file
- 5. Separating only the tests that need the logged-out state
- 6. Setup runs on every execution
- 7. Error when the saved file is missing
- 8. Error when the session expires on the server
The login-enabled app used for testing
Using only Node.js's http module, I wrote a server (server.mjs) with the following behavior:
/loginhas email and password fields and a login button- On correct input, it waits 1 second, returns the cookie
sid, and moves to/dashboard /dashboardand/settingsredirect to/loginwhen there is nosid. When opened, they writethemeto localStorage- Sessions are held only in server memory, so they disappear when the server restarts
The 1-second wait on login is there to reproduce a slow login. The server counts each login it receives and writes the count to the log. It also returns the count when /__logins is opened. Playwright starts it through webServer in the config.
Logging in before every test
As a comparison, I first tried the approach that does not use saved state. In beforeEach, the test types the credentials on the login screen before every test.
// tests-no-reuse/member.spec.ts
import { test, expect } from '@playwright/test';
// Log in before every test, without reusing a saved state
test.beforeEach(async ({ page }) => {
await page.goto('/login');
await page.getByLabel('メールアドレス').fill('demo@example.com');
await page.getByLabel('パスワード').fill('password123');
await page.getByRole('button', { name: 'ログイン' }).click();
await page.waitForURL('/dashboard');
});
test('ダッシュボードを開ける', async ({ page }) => {
await page.goto('/dashboard');
await expect(page.getByRole('heading', { name: 'ダッシュボード' })).toBeVisible();
});
// Two more tests: one opens the settings page, and one checks that the logged-in email address is shown
All three tests passed. The server log and /__logins, which returns the count, show that it received three logins.
$ npx playwright test -c playwright.no-reuse.config.ts
Running 3 tests using 1 worker
✓ 1 [chromium] › tests-no-reuse/member.spec.ts:12:5 › ダッシュボードを開ける (1.2s)
✓ 2 [chromium] › tests-no-reuse/member.spec.ts:17:5 › 設定を開ける (1.2s)
✓ 3 [chromium] › tests-no-reuse/member.spec.ts:22:5 › ログイン中のメールアドレスが出る (1.1s)
3 passed (4.0s)
$ cat server.log; echo; echo "ログインの回数: $(curl -s localhost:3100/__logins)"
[server] http://localhost:3100
[server] ログイン 1 回目
[server] ログイン 2 回目
[server] ログイン 3 回目
ログインの回数: 3
Playwright Test creates a new browser context for each test (see the official test isolation explanation). Cookies from a login in one test do not carry over to the next, so each added test adds another login.
Logging in once in a setup project and saving the state
Following the approach in the official authentication page, I created a setup project that handles only login.
First is tests/auth.setup.ts, which logs in and saves the state to a file. The final page.context().storageState({ path }) writes the browser context's cookies and localStorage to the file.
// tests/auth.setup.ts
import { test as setup, expect } from '@playwright/test';
const authFile = 'playwright/.auth/user.json';
setup('ログインして状態を保存する', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('メールアドレス').fill('demo@example.com');
await page.getByLabel('パスワード').fill('password123');
await page.getByRole('button', { name: 'ログイン' }).click();
// Wait until the page after the cookie is set, then save
await page.waitForURL('/dashboard');
await expect(page.getByText('demo@example.com でログイン中')).toBeVisible();
await page.context().storageState({ path: authFile });
});
Before saving, the code waits for the URL and display after login. The official documentation also notes that a cookie may be set during a redirect in the middle of login, so it recommends waiting until the final URL or the page shown after the cookie is set before saving.
Next is playwright.config.ts. For the chromium project, which runs the regular tests, I specify two things:
storageState: the file to load when a test startsdependencies: ['setup']: run the setup project first
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
reporter: 'list',
use: { baseURL: 'http://localhost:3100' },
webServer: {
command: 'node server.mjs',
url: 'http://localhost:3100/login',
reuseExistingServer: true,
},
projects: [
// Project that only logs in and saves the state
{ name: 'setup', testMatch: /.*\.setup\.ts/ },
{
name: 'chromium',
testIgnore: /.*\.setup\.ts/,
use: {
...devices['Desktop Chrome'],
// Start by loading the state that setup saved
storageState: 'playwright/.auth/user.json',
},
dependencies: ['setup'],
},
],
});
The test files contain no login code. page is passed in already logged in.
// tests/member.spec.ts
import { test, expect } from '@playwright/test';
test('ダッシュボードを開ける', async ({ page }) => {
await page.goto('/dashboard');
await expect(page.getByRole('heading', { name: 'ダッシュボード' })).toBeVisible();
});
// Two more tests: one opens the settings page, and one checks that the logged-in email address is shown
When I ran it, [setup] ran once first, and then the [chromium] tests ran. The server received only one login.
$ npx playwright test
Running 5 tests using 2 workers
✓ 1 [setup] › tests/auth.setup.ts:5:6 › ログインして状態を保存する (1.2s)
✓ 3 [chromium] › tests/guest.spec.ts:6:5 › ログインしていないとログイン画面に戻される (109ms)
✓ 2 [chromium] › tests/member.spec.ts:3:5 › ダッシュボードを開ける (167ms)
✓ 4 [chromium] › tests/member.spec.ts:8:5 › 設定を開ける (93ms)
✓ 5 [chromium] › tests/member.spec.ts:13:5 › ログイン中のメールアドレスが出る (87ms)
5 passed (2.5s)
$ cat server.log; echo; echo "ログインの回数: $(curl -s localhost:3100/__logins)"
[server] http://localhost:3100
[server] ログイン 1 回目
ログインの回数: 1
guest.spec.ts is the test for the logged-out state, which I describe later.

Each test that logs in took 1.1 to 1.2 seconds. Tests that load the saved state took 87 to 167 milliseconds each. Most of this difference, however, comes from the 1-second wait I deliberately put in the test server. How much faster this is in practice depends on how long your app's login takes.
Contents of the saved file
playwright/.auth/user.json contained the following (the value is generated by the server and changes on every run):
{
"cookies": [
{
"name": "sid",
"value": "3f7a9889-afb0-4d71-b822-daf70d6b009c",
"domain": "localhost",
"path": "/",
"expires": -1,
"httpOnly": true,
"secure": false,
"sameSite": "Lax"
}
],
"origins": [
{
"origin": "http://localhost:3100",
"localStorage": [
{
"name": "theme",
"value": "dark"
}
]
}
]
}
The cookie with httpOnly: true was saved as is. localStorage is stored per origin inside origins. sessionStorage, on the other hand, is not saved. The official explanation of how to save sessionStorage says there is no API for saving sessionStorage, and shows an example of code that saves and loads it yourself.
Anyone with the cookies in this file can be logged in as the test account. The official documentation strongly recommends not committing it to the repository. Add playwright/.auth to .gitignore.
In my test environment, I added the single line playwright/.auth to .gitignore and used git check-ignore to confirm that the file is ignored.
$ git check-ignore -v playwright/.auth/user.json
.gitignore:2:playwright/.auth playwright/.auth/user.json
Separating only the tests that need the logged-out state
When storageState is set, every test in that project starts logged in. For files that need the logged-out state, such as a test that checks you are sent back to the login screen, specify an empty state with test.use. This is also the approach shown in the official documentation.
// tests/guest.spec.ts
import { test, expect } from '@playwright/test';
// Only this file does not use the saved state (starts logged out)
test.use({ storageState: { cookies: [], origins: [] } });
test('ログインしていないとログイン画面に戻される', async ({ page }) => {
await page.goto('/dashboard');
await expect(page).toHaveURL('/login');
});
As shown in the results above, this test passed by being redirected to /login.
Setup runs on every execution
When I ran npx playwright test again, [setup] ran again as well, and the server's login count went to 2. Even when the saved file still exists, the dependency project runs every time. The official explanation of project dependencies also states that a dependency always runs first.
If you run tests many times locally and want to skip that login each time, select only the chromium project with --project=chromium and add --no-deps. --no-deps is an option that does not run dependencies, so only the directly selected project runs (see the command-line option list). Since the file saved earlier was still there, the tests passed without logging in.
$ npx playwright test --project=chromium --no-deps
Running 4 tests using 2 workers
✓ 1 [chromium] › tests/guest.spec.ts:6:5 › ログインしていないとログイン画面に戻される (100ms)
✓ 2 [chromium] › tests/member.spec.ts:3:5 › ダッシュボードを開ける (154ms)
✓ 3 [chromium] › tests/member.spec.ts:8:5 › 設定を開ける (90ms)
✓ 4 [chromium] › tests/member.spec.ts:13:5 › ログイン中のメールアドレスが出る (88ms)
4 passed (868ms)
After this run, the server's login count stayed at 2. With --no-deps, however, the result depends on the state of the saved file. The following two errors both occurred with --no-deps.
Error when the saved file is missing
I deleted playwright/.auth/user.json and ran with --no-deps. The tests failed right away without opening any page (I shortened the separator lines and omitted the errors after the first).
$ rm playwright/.auth/user.json; npx playwright test --project=chromium --no-deps tests/member.spec.ts
Running 3 tests using 1 worker
✘ 1 [chromium] › tests/member.spec.ts:3:5 › ダッシュボードを開ける (5ms)
✘ 2 [chromium] › tests/member.spec.ts:8:5 › 設定を開ける (3ms)
✘ 3 [chromium] › tests/member.spec.ts:13:5 › ログイン中のメールアドレスが出る (3ms)
1) [chromium] › tests/member.spec.ts:3:5 › ダッシュボードを開ける ───
Error: Error reading storage state from playwright/.auth/user.json:
ENOENT: no such file or directory, open 'playwright/.auth/user.json'
If you see Error reading storage state from, check whether setup has not run, or whether the save path and the path in storageState do not match. Running without --no-deps makes setup run first and create the file.
Error when the session expires on the server
Even when the file exists, if the cookies inside are no longer valid on the server, the tests fail after being redirected to the login screen. In my test, I saved the file with setup, restarted the server to clear the sessions held in memory, and then ran with --no-deps (I shortened the separator lines and omitted the second half of the error).
$ npx playwright test --project=chromium --no-deps tests/member.spec.ts -g "ダッシュボード"
Running 1 test using 1 worker
✘ 1 [chromium] › tests/member.spec.ts:3:5 › ダッシュボードを開ける (5.1s)
1) [chromium] › tests/member.spec.ts:3:5 › ダッシュボードを開ける ───
Error: expect(locator).toBeVisible() failed
Locator: getByRole('heading', { name: 'ダッシュボード' })
Expected: visible
Timeout: 5000ms
Error: element(s) not found
The error only says that the heading could not be found, which makes it hard to see right away that login is the cause. When I opened the error-context.md that is saved on failure, I could see that the page at that moment was the login screen.
- heading "ログイン" [level=1]
- text: メールアドレス
- textbox "メールアドレス"
- text: パスワード
- textbox "パスワード"
- button "ログイン"
The official documentation says that when a saved state expires, you need to delete the file. If you run setup every time without --no-deps during normal runs, the state is saved again with a new cookie on each run.





