October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
authentication state

How to Reuse Browser Profiles for Automation (Safely with Playwright)

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a dedicated Playwright profile when you need browser state to survive restarts; use a saved authentication-state file when you need many isolated test contexts. Never point automation at the Chrome profile you use every day, and never run two browsers against the same user-data directory. The examples below show both approaches, explain what each stores, and include recovery and security steps.

Choose the persistence model first

“Reuse a browser profile” can mean three different things in Playwright. Selecting the right one prevents locked directories, accidental credential sharing and tests that pass only because they depend on an operator’s desktop session.

Method What persists Isolation Concurrency and best fit
Persistent user-data directory Broad browser profile state, including cookies and local storage One persistent context for the directory The directory cannot be launched by multiple simultaneous browser instances; best for a continuing profile
Saved authentication state loaded into contexts Cookies, local storage, IndexedDB and passkey (WebAuthn) state; session storage needs separate handling Each test can create an isolated context with preloaded state Better for parallel or independent tests; the state file is still sensitive
In-memory session State only while the live browser session remains open Session-scoped State disappears at browser close; useful when nothing should be written to disk

These behaviors are documented in Playwright’s BrowserType API, Authentication guide and CLI sessions documentation.

Use a dedicated persistent profile

Why a separate directory matters

Chromium’s user-data directory is the parent directory of the profile path shown at chrome://version. Do not copy only a profile subfolder and assume it is the user-data directory. More importantly, do not reuse your normal Chrome “User Data” directory. Playwright warns that recent Chrome policy changes make automating the default profile unsupported; pages may fail to load or the browser may exit.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Create a directory used only by automation, such as ./.pw-profile. Keep it outside source control and use a test account rather than a personal account.

JavaScript example

import { chromium } from 'playwright';

const context = await chromium.launchPersistentContext('./.pw-profile', {
  headless: false,
  viewport: { width: 1440, height: 900 }
});

const page = context.pages()[0] || await context.newPage();
await page.goto('https://example.test/account');
console.log('Title:', await page.title());

// Keep the profile data on disk, then close cleanly.
await context.close();

launchPersistentContext(userDataDir) returns the browser’s only context. Closing that context closes the browser. Cookies and local storage written during the run are available the next time you launch with the same directory.

Python example

from pathlib import Path
from playwright.sync_api import sync_playwright

profile = Path('.pw-profile').resolve()
with sync_playwright() as p:
    context = p.chromium.launch_persistent_context(
        user_data_dir=str(profile),
        headless=False,
        viewport={"width": 1440, "height": 900},
    )
    page = context.pages[0] if context.pages else context.new_page()
    page.goto("https://example.test/account")
    print(page.title())
    context.close()

First-run sign-in workflow

  1. Launch the persistent context with the empty automation directory.
  2. Navigate to the sign-in page and authenticate manually or through your authorized test flow.
  3. Verify the account page is available.
  4. Close the context normally so Chromium flushes profile data.
  5. Run the same script again; it should open with the stored cookies and local storage.

Do not launch a second process with that directory while the first browser is open. Browsers do not allow multiple instances to use the same user-data directory, so a second process can fail with a lock or an unavailable profile.

Save authenticated state for isolated contexts

When this is the better design

Persistent profiles are broad and convenient, but one directory represents one live browser. For a test suite, a more reproducible pattern is to authenticate once, save the state, and load it into fresh contexts. Each worker then gets its own cookies and storage namespace while starting signed in.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Playwright’s built-in state covers cookies, local storage, IndexedDB and passkey authentication. Session storage is not included; if your application keeps the login token only there, use a separate custom save/load mechanism rather than assuming storageState will contain it.

Create the state file

import { chromium } from 'playwright';

const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://example.test/login');
await page.getByLabel('Email').fill(process.env.TEST_EMAIL);
await page.getByLabel('Password').fill(process.env.TEST_PASSWORD);
await page.getByRole('button', { name: 'Sign in' }).click();
await page.waitForURL('**/account');
await page.context().storageState({ path: 'playwright/.auth/state.json' });
await browser.close();

Load it in a new test context

import { chromium } from 'playwright';

const browser = await chromium.launch();
const context = await browser.newContext({
  storageState: 'playwright/.auth/state.json'
});
const page = await context.newPage();
await page.goto('https://example.test/account');
console.log(await page.locator('[data-test=user-name]').textContent());
await context.close();
await browser.close();

Create a fresh context per test or worker when isolation matters. Multiple contexts may read the same state file, but they should not write back to one shared mutable profile directory.

Protect the state file

The JSON file can contain cookies and headers capable of impersonating the account. Playwright strongly discourages checking it into a repository. Put it in a git-ignored directory, restrict filesystem permissions, keep it out of bug reports and delete or rotate it when the test account or session is no longer valid. Treat it like a password, not a harmless fixture.

Understand in-memory versus disk persistence

An ordinary Playwright CLI session keeps its session data in memory: commands in that live session can share state, but closing the browser loses it. The CLI documents a --persistent option when you need disk persistence. Profile and default behavior differ between Playwright CLI, Playwright MCP and library APIs, so check the configuration for the exact tool and version you run.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Playwright MCP offers persistent and isolated modes. Its documented profile location is derived from the platform and workspace, and one profile can be used by only one browser at a time. For CI, explicit per-worker directories or preloaded storage state are less surprising than relying on a machine-wide default.

Prevent collisions in CI and parallel workers

  • Give every simultaneous persistent browser a unique directory, for example .profiles/worker-1 and .profiles/worker-2.
  • Delete stale temporary directories after a worker exits, but preserve a deliberately seeded profile only when the workflow requires it.
  • Use saved authentication state plus new contexts when tests need parallelism without sharing browser caches, extensions or history.
  • Do not “fix” a lock by killing an unrelated Chrome process; identify the process that owns the automation directory first.
  • Run profile creation and state generation in a setup job, then distribute protected artifacts to workers through your CI secret mechanism.

A profile directory is not a safe coordination mechanism. If two jobs need the same account, coordinate the account’s data and server-side test fixtures separately; do not make them write one live Chromium profile concurrently.

Authentication edge cases

Multi-factor authentication

Prefer a dedicated test identity with a controlled MFA method. A saved state can expire or be revoked, and a persistent profile can still require a new challenge after a policy change. Build an explicit re-authentication path rather than attempting to bypass MFA or other access controls.

Session-only storage

If the application stores its token in sessionStorage, Playwright’s built-in storage-state file will not preserve it. Save and restore that data with an application-specific, access-controlled mechanism, or change the test login flow to use cookies or local storage that the application intentionally supports for testing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Passkeys and WebAuthn

Playwright documents passkey (WebAuthn) state as supported by authenticated storage state. Keep the state tied to the same authorized test environment and expect registration or policy changes to invalidate old artifacts.

Troubleshooting checklist

Browser exits immediately or pages never load

Cause: the script points at your everyday Chrome user-data directory or a profile subfolder instead of a dedicated directory. Fix: create a new automation directory and pass its parent path to launchPersistentContext.

“Profile in use” or lock errors

Cause: another browser instance still owns the directory. Fix: close the first context, wait for the process to exit, then retry; for parallel work, assign unique directories.

The test opens logged out

Cause: the state file was created before login completed, the session expired, or the application relies on session storage. Fix: wait for a post-login URL or element before saving, regenerate the state, and handle session storage separately if required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

State works locally but not in CI

Cause: an absolute path, browser version, origin, hostname or secret differs. Fix: use a workspace-relative path, verify the target origin and environment variables, install the same Playwright browser version, and generate state inside the CI environment when practical.

Tests interfere with one another

Cause: shared persistent directories, shared accounts or mutable server data. Fix: isolate contexts and profile directories, use independent test data, and serialize only the operations that genuinely require one account.

Performance, reliability and cost decisions

  • Startup: a persistent profile may be slower and larger because it carries caches, extensions and history. Keep the profile minimal and avoid installing unnecessary extensions.
  • Repeatability: saved state plus a new context reduces hidden local variation, while a long-lived profile can accumulate banners, experiments and stale service-worker data.
  • Failure recovery: if a persistent directory becomes corrupted or locked beyond recovery, close all owners and recreate it from a known login flow. Keep the state artifact reproducible rather than copying a personal profile.
  • Disk hygiene: temporary profiles can contain sensitive data and grow over time. Store them on an appropriate encrypted workspace and remove them after the run.
  • Server-side limits: profile reuse does not grant permission to evade bot checks, rate limits or site rules. Automate only systems and accounts you are authorized to test.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your actual goal is a clean screenshot rather than an interactive signed-in test, ScreenshotNeo provides a website screenshot API and MCP server. It accepts a URL in one request and returns PNG, JPEG, WebP or PDF. Before capture it accepts cookie/consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets; each step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and the response reports the result in X-Page-Verdict and X-Billed headers. Its MCP tools—take_screenshot, get_page_info and capture_pdf—work with Claude, Cursor and other MCP clients.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo documentation for all options, including full-page and element capture, device presets, custom CSS and JavaScript, waits, headers, cookies, geolocation, PDF controls, signed links, asynchronous jobs and bulk capture.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Free accounts include 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is on every plan. Create a free ScreenshotNeo account.

Frequently asked questions

Can I copy my normal Chrome profile into automation?

Do not use the live default profile. Create a separate automation directory and authenticate a test account there.

Does storage state include every kind of browser data?

No. It includes documented cookies, local storage, IndexedDB and passkey state, but not session storage without a separate custom mechanism.

Can two Playwright workers share one persistent directory?

No. One browser instance at a time may use a user-data directory. Give workers separate directories or load protected state into isolated contexts.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Is an authentication JSON file safe to commit if the password is not present?

No. Cookies and headers in the file may be enough to impersonate the account. Keep it private, git-ignored and short-lived.

Frequently Asked Questions

Which persistence method should a parallel test suite use?

Generate authenticated storage state once, then create a new isolated context for each worker or test. Reserve a persistent directory for workflows that genuinely need a continuing full browser profile.

How do I preserve sessionStorage between Playwright runs?

The built-in storage-state API does not persist sessionStorage. Implement a separate, access-controlled save/load routine for that application data.

What should I do when a reusable profile is stale?

Close every browser using it, remove or archive the directory, and recreate it through the authorized login flow rather than copying a personal Chrome profile.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.