storageState to sign in once and load a saved snapshot into fresh contexts. Start with a setup project and a protected-page smoke test.indexedDB: true if your app stores auth there. sessionStorage needs separate handling.Playwright storage state is a snapshot of selected browser-side data. Calling context.storageState({ path }) writes it to a JSON file. A later browser.newContext({ storageState: path }) starts a fresh context seeded with that data. Playwright Test applies the same idea when you set use.storageState in a project.
| Storage | Included by default? | What to check |
|---|---|---|
| Cookies | Yes | Compare the cookie domain and path with the actual protected URL. The browser applies cookie security and expiry rules when sending a request. |
localStorage |
Yes | A snapshot for https://qa.example.com belongs to that origin. Switching scheme, host, or port changes the origin. |
| IndexedDB | No | Pass indexedDB: true when saving if the app keeps its login state in IndexedDB. The option was added in Playwright 1.51. |
sessionStorage |
No | It is scoped to an origin and tab. A new context has a new page session. Seed the required key before app code runs if your authorized test needs it. |
See the storageState API reference for the complete list of options. The sessionStorage reference explains what persists through reloads in the same tab.
The snapshot contains data the browser can present to your app. Your server still decides whether the session is valid. A well-formed JSON file can point to an expired session, a revoked account, or a refresh token your app has already rotated.
Use the setup-project method for an end-to-end suite and a persistent context when you deliberately need the same browser directory on successive launches.
You need a Node.js project with @playwright/test and its Chromium browser installed, plus a staging or local app you are authorized to test. Set QA_BASE_URL, QA_USER, and QA_PASSWORD in the process environment. The examples assume /login has labeled Email and Password fields and a Sign in button. A successful login lands on /account, which shows Account dashboard. Replace the routes and locators with your app's equivalents.
Create playwright.config.ts. The dependency makes the setup project run before tests in authenticated. Keep an independent login test in a project without inherited auth when you need to verify the login itself.
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: './tests',
use: { baseURL: process.env.QA_BASE_URL ?? 'http://127.0.0.1:4173' },
projects: [
{ name: 'setup', testMatch: /auth\.setup\.ts$/, use: { trace: 'off' } },
{
name: 'authenticated',
testMatch: /.*\.spec\.ts$/,
dependencies: ['setup'],
use: { storageState: 'playwright/.auth/viewer.json' },
},
],
});
Add playwright/.auth/ and .qa-browser/ to .gitignore before running the examples. Use a dedicated test account and keep state files and browser data directories out of CI uploads. Treat traces of authenticated tests as sensitive artifacts too.
Create tests/auth.setup.ts. This setup checks credentials are present, waits for the redirect, and checks a signed-in UI element before saving. If your app populates a token after the initial page render, wait for the authenticated response or the relevant UI state before taking the snapshot.
import { test, expect } from '@playwright/test';
import { mkdir } from 'node:fs/promises';
const statePath = 'playwright/.auth/viewer.json';
test('save viewer login', async ({ page }) => {
const { QA_USER, QA_PASSWORD } = process.env;
if (!QA_USER || !QA_PASSWORD) {
throw new Error('Set QA_USER and QA_PASSWORD for the test account.');
}
await page.goto('/login');
await page.getByLabel('Email').fill(QA_USER);
await page.getByLabel('Password').fill(QA_PASSWORD);
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page).toHaveURL(/\/account$/);
await expect(page.getByRole('heading', { name: 'Account dashboard' })).toBeVisible();
await mkdir('playwright/.auth', { recursive: true, mode: 0o700 });
await page.context().storageState({ path: statePath });
});
For an IndexedDB-backed app, change the last call to storageState({ path: statePath, indexedDB: true }) after the app finishes writing auth data. An auth cookie can be HTTP-only and still appear in the snapshot. Keep the JSON private and avoid printing it while debugging.
Create tests/account.spec.ts. It opens the protected URL in a fresh Playwright Test context, then checks the same URL in a second context with an explicitly empty snapshot. The empty snapshot overrides the authenticated project defaults. This check can catch a test that passes because the route is public. See the context option inheritance rules.
import { test, expect } from '@playwright/test';
test('reuses the saved login and protects the signed-out route', async ({ page, browser, baseURL }) => {
await page.goto('/account');
await expect(page.getByRole('heading', { name: 'Account dashboard' })).toBeVisible();
const signedOut = await browser.newContext({
baseURL,
storageState: { cookies: [], origins: [] },
});
try {
const signedOutPage = await signedOut.newPage();
await signedOutPage.goto('/account');
await expect(signedOutPage).toHaveURL(/\/login$/);
} finally {
await signedOut.close();
}
});
Run npx playwright test --project=authenticated from the project root. If you run in UI mode, run the setup project manually when state is missing or expires. The Playwright authentication guide describes the setup dependency, UI mode, and worker-scoped fixtures.
chromium.launchPersistentContext(userDataDir) starts a browser backed by the given data directory and returns its context. Use it for a repeated local QA workflow when the same browser environment matters. Launch that directory serially and close the context at the end of each run. Use a new test directory for each role or environment, away from your daily Chrome profile. The persistent context API reference documents the single-directory concurrency limit and default Chrome profile restriction.
Save this as staging-profile.mjs. The first run signs in if /account redirects to /login. A later run checks the same protected page using persisted browser data. The decision still depends on the app accepting the existing session. For a multi-step sign-in or MFA flow, use your approved staging login process and verify the final signed-in view before closing.
import { chromium, expect } from '@playwright/test';
import { resolve } from 'node:path';
const baseURL = process.env.QA_BASE_URL ?? 'http://127.0.0.1:4173';
const context = await chromium.launchPersistentContext(
resolve('.qa-browser', 'staging-viewer'),
{ baseURL },
);
try {
const page = context.pages()[0] ?? await context.newPage();
await page.goto('/account');
if (new URL(page.url()).pathname === '/login') {
const { QA_USER, QA_PASSWORD } = process.env;
if (!QA_USER || !QA_PASSWORD) {
throw new Error('Set QA_USER and QA_PASSWORD for the test account.');
}
await page.getByLabel('Email').fill(QA_USER);
await page.getByLabel('Password').fill(QA_PASSWORD);
await page.getByRole('button', { name: 'Sign in' }).click();
}
await expect(page).toHaveURL(/\/account$/);
await expect(page.getByRole('heading', { name: 'Account dashboard' })).toBeVisible();
} finally {
await context.close();
}
Run node staging-profile.mjs twice against the same staging URL and profile directory. For a cookie-based app, check whether the cookie has a persistent expiry when the second run still needs to sign in. Also check whether browser shutdown rules cleared the data or the server invalidated the session. A persistent directory does not extend the lifetime of server-side credentials.
Use one state file per role and test environment. Multiple workers can load the same read-only baseline in fresh contexts when the app permits it. Those contexts can still point to a single server-side identity. For example, two settings tests can overwrite each other's records even when their tabs and cookies are isolated.
| Workflow | State boundary | Watch for |
|---|---|---|
| Read-only dashboard suite | One snapshot per environment and role | An expired baseline or app rules that cap concurrent sessions. |
| Tests that edit user settings | One test identity per parallel worker and a worker-scoped storageState fixture |
Duplicate accounts across CI shards. parallelIndex is local to the run, so reserve accounts across jobs or include a job identifier in the allocation. |
| Checkout or admin approvals | Distinct role files, separate contexts, and unique test records | The test creates a valid session for the wrong role. Assert the expected workspace and role after loading state. |
| Sign-out, password change, and session expiry | A fresh or dedicated test identity | These actions can invalidate a shared session and cause unrelated tests to fail. |
For a worker-scoped fixture, create a context with explicitly empty storage state, sign in with the worker's allocated account, and save that account's state under a run-specific path. Return the path from the fixture to storageState so the standard page fixture still starts each test in a fresh context. Keep account provisioning and record cleanup separate from browser setup.
Start by comparing the first protected request in a fresh context with the same request just after login. Check the final URL and response status. If the browser sent the right session cookie but the protected request still returned 401 or redirected, inspect the staging application's session logs before changing browser waits.
| Symptom | What to inspect | What to change |
|---|---|---|
| State file missing | Setup project result, current directory, and configured state path | Run the project dependency or manually rerun setup in UI mode. Keep writer and reader paths identical. |
Headed setup works, CI reopens /login |
Effective baseURL, cookie scope and expiry, and whether the account works from that staging environment |
Generate state in the same test run and wait for an actual authenticated response or signed-in view before saving. |
| Cookie is present, app still looks signed out | Auth token location in the app, including IndexedDB or sessionStorage |
Enable IndexedDB capture if that is the store. For sessionStorage, use a fixture that calls context.addInitScript() before the first navigation, scoped to the exact test origin and the key the app needs. Keep it out of sign-out tests. |
| Tests pass alone but fail in parallel | Which accounts or records each worker changed, plus any session rotation | Allocate unique test accounts and records and rerun in parallel. |
| Persistent context fails to start | Absolute userDataDir and any live processes using it |
Close the matching context or allocate a new test directory. |
When state has expired, regenerate it through normal sign-in. In a team runbook, record which environment and role own the file, where fresh state is generated, and which failing check signals that it is time to regenerate.
A test suite and a QA handoff often have different needs. Keep the suite on Playwright setup projects so CI can generate fresh state independently. When two authorized testers need to reproduce a browser-specific issue, Nstbrowser can give each staging environment a named Profile. A name such as Checkout QA — Staging Viewer tells the next tester which workspace and role to verify. Team permissions can scope who can open the relevant Profile group. Your staging app continues to control who can sign in and what each user can do.
Run the setup project against one test account and prove a fresh context can open a protected URL. Add separate role and worker state when the suite needs it. If a teammate also needs a named test workspace for manual reproduction, set up one staging Profile and document the role, URL, and expected page in the handoff.
Yes. The default storageState() snapshot includes cookies and local storage. Set indexedDB: true if your app stores important auth data in IndexedDB, and verify the result in a fresh context.
Yes. For tests that only read data, multiple fresh contexts can load the same starting snapshot if your app allows concurrent use of the session. Give workers distinct accounts when they change account-level settings or can sign each other out.
It can when you reopen the same dedicated directory and your app still accepts the persisted session. A session-only cookie, browser cleanup, or server-side invalidation can require a fresh login.
Test it against the target browser and the same staging origin. If auth depends on browser characteristics, different network conditions, or an environment-specific login policy, generate the snapshot inside each target project or CI job using its authorized test credentials.