CAPTCHA solving is now available in Nstbrowser, with support for 5 CAPTCHA types.

Learn More

🚀

Platform Proxy is live in Nstbrowser — built-in proxies from$0.4/GB.

Start Now

  • Pricing
  • Documentation
EN
Contact

© 2026 NST LABS TECH LTD. ALL RIGHTS RESERVED

Products

Anti-Detect Browser
Nstbrowser RPA
AI Agent Skills
Proxy
Cloudflare Bypass
Web Unblocker

Solutions

Cloud Fingerprint Browser
Multi-Account Management
Web Scraping & Automation
Anti-Bot Solutions
Data Isolation for Enterprise Security
Claude AI IP Checker

Resources

Pricing
Download
RPA Marketplace
Affiliate Program
Partners
Blog
Release Notes

Support

Contact

Documentation

Legal

Terms
Privacy Policy
Cookies Policy

ProductsSolutionsResourcesSupportLegal

ProductsSolutionsResources

SupportLegal

© 2026 NST LABS TECH LTD. ALL RIGHTS RESERVED

Back to Blog
How to save and reuse login state in Playwright
playwrightbrowser-automation

How to Save and Reuse Login State in Playwright

Save Playwright login state for fresh test contexts, compare it with persistent contexts, and fix expired sessions, missing tokens, and parallel test conflicts.
Nov 25, 2026Carlos Rivera

TL;DR

  • Use Playwright storageState to sign in once and load a saved snapshot into fresh contexts. Start with a setup project and a protected-page smoke test.
  • The default snapshot includes cookies and local storage. Add indexedDB: true if your app stores auth there. sessionStorage needs separate handling.
  • Use separate test accounts for workers that change shared data. Browser isolation leaves the server-side account and its records shared.
  • A Playwright persistent context keeps a dedicated browser data directory across launches. It works well for a serial debugging workflow on one machine.

What Does Playwright Storage State Save?

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.

How to Save and Reuse Playwright Storage State

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.

Method 1 · Use a Setup Project for Your Test Suite

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.

Step 1: Configure a Setup Project and an Authenticated Project

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.

ts Copy
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.

Step 2: Sign In and Save a Verified Session

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.

ts Copy
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.

Step 3: Prove a Fresh Context Can Open a Protected Page

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.

ts Copy
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.

Method 2 · Use a Playwright Persistent Context for Serial Debugging

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.

js Copy
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.

How to Separate Login State Across Roles, Workers, and CI Shards

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.

How to Diagnose a Saved Session That Still Redirects to Login

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.

How QA Teams Can Organize Staging Profiles With Nstbrowser

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.

  • Confirm the environment. Follow the Profile setup guide to create a separate staging Profile. Open the approved test URL and verify the environment banner and role before collecting evidence.
  • Give testers scoped access. Use Team Management to assign the QA team to the intended Profile group. Have testers sign in with their own authorized test identities. In the handoff, share the reproduction URL and steps and keep state files private.
  • Document the Playwright connection independently. For an approved workflow that needs to attach to a managed Profile, use Nstbrowser's Playwright API guide to check the Client or Docker prerequisites. The Playwright examples above use local Chromium and work independently of a managed Profile.
Try for Free >

Start With One Protected-Page Check

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.

Try for Free >

FAQ

Does Playwright storage state save cookies and local storage?

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.

Can I use the same state file in multiple tests?

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.

Does a Playwright persistent context keep me logged in after a restart?

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.

Can I reuse a storage state file in another browser or CI runner?

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.

More
How to save and reuse login state in Playwright
playwrightbrowser-automation
How to Save and Reuse Login State in Playwright
Save Playwright login state for fresh test contexts, compare it with persistent contexts, and fix expired sessions, missing tokens, and parallel test conflicts.
Nov 25, 2026Carlos Rivera
Best Agentic Browsers: A Workflow-Based Selection Guide — Nstbrowser cover
ai-agentbrowser-automation
Best Agentic Browsers for Web Tasks and Automation
Compare Nstbrowser AI Agent, Browser Use, Stagehand, and Chrome DevTools MCP by session control, execution model, debugging, and evaluation criteria.
Nov 11, 2026Carlos Rivera
Antidetect Browser API Troubleshooting: Common Errors & Fixes — Nstbrowser cover
browser-automationprofile-management
Antidetect Browser API Troubleshooting: Common Errors and Fixes
Troubleshoot an antidetect browser API by isolating service, authentication, request, profile startup, and framework attachment failures in order.
Nov 10, 2026Carlos Rivera
Browser Automation API: Profile Management Guide — Nstbrowser cover
browser-automationprofile-management
Browser Automation API for Profile Management: A Practical Guide
Build a clear Nstbrowser API v2 lifecycle for saved profiles: prepare, launch, inspect connection details, attach automation, and stop the browser.
Nov 10, 2026Carlos Rivera
Browser Multi-Window Synchronizer: How It Works & When to Use It — Nstbrowser cover
browser-automationprofile-management
Browser Multi-Window Synchronizer: How It Works and When to Use It
Understand browser multi-window synchronization, suitable tasks, common alignment problems, and how to evaluate Nstbrowser for coordinated workflows.
Nov 10, 2026Carlos Rivera
Bulk Create Browser Profiles: A Practical Nstbrowser Guide — Nstbrowser cover
browser-automationprofile-management
How to Bulk Create Browser Profiles in Nstbrowser
Learn how to bulk create browser profiles in Nstbrowser, assign groups and proxies, validate a pilot batch, and avoid common setup mistakes.
Nov 10, 2026Carlos Rivera
Catalogue