Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
browser automation

Persistent Browser Sessions and Profiles: A Practical Playwright Guide

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

Use a dedicated, disk-backed browser profile when a workflow must stay logged in after the browser closes. In Playwright, that means launchPersistentContext(userDataDir). Use a saved storageState file instead when you need a reproducible authenticated test setup, and use isolated contexts or separate profile directories when accounts or jobs must not share data.

Persistence is convenient, but it also preserves cookies, local storage and other credentials. A profile directory has a single-browser-owner rule, and an authentication-state file must be protected like a password.

What a persistent browser session actually stores

A normal, in-memory browser context disappears when the process closes. A persistent context writes browser data to a user-data directory, so a later run can reuse the state. Depending on the browser and workflow, that state can include cookies, local storage, IndexedDB, cache, history, tabs, settings and passkeys.

Playwright’s launchPersistentContext(userDataDir) is the direct implementation. The directory is a complete automation profile, not just a cookie jar. Only one browser instance may use a particular directory at a time.

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.

Choose the right persistence model

Approach Survives restart? What it covers Best fit
In-memory context No State for the current process Clean, independent tests
Persistent context Yes Profile data such as cookies, local storage, IndexedDB, cache and history Long-lived automation or a developer login profile
storageState Yes, through a file Cookies, local storage, IndexedDB and passkeys; not sessionStorage automatically Reproducible authenticated test setup
Playwright CLI named session With --persistent Cookies, localStorage, IndexedDB, cache, history, tabs and console logs Interactive CLI work that must continue later
Firefox profile Yes Bookmarks, passwords, settings, add-ons, history, cookies and logins Complete Firefox data separation
Firefox container Within one profile Narrower separation of browsing data such as cookies and logins Multiple identities without separate full profiles

Use a persistent Playwright profile

1. Create a dedicated directory

Choose a path used only by automation, such as .automation/chrome-account-a. Do not point Playwright at your everyday Chrome profile. A dedicated directory prevents test changes from corrupting personal bookmarks, extensions or login state and makes deletion or rotation deliberate.

2. Launch the context and reuse its page

The persistent launch returns a browser context directly; you do not create a second context from it.

import { chromium } from 'playwright';

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

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

// Keep the profile on disk for the next run.
await context.close();

On the first run, log in through the visible browser. On subsequent runs, the site can read the saved cookies and storage from that directory. Closing the context flushes changes; force-killing the process can leave incomplete state, so graceful shutdown matters.

3. Make ownership explicit

Never start two processes against the same directory. For parallel jobs, assign one directory per account or job, for example profiles/account-a and profiles/account-b. A lock, queue or CI job scheduler should enforce that rule rather than allowing two workers to race.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Use storageState for a reproducible login

A full persistent profile is useful when you need browser-wide state. For tests, a smaller serialized state is often easier to create, review operationally and distribute to a controlled runner. Playwright’s authentication workflow can restore cookies, local storage, IndexedDB and passkeys from a state file.

Save state after an interactive login

import { chromium } from 'playwright';

const browser = await chromium.launch({ headless: false });
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://example.com/login');

// Complete the login in the browser, then save the authenticated state.
await page.waitForURL('**/account');
await context.storageState({ path: 'playwright/.auth/account-a.json' });
await browser.close();

Restore it in a clean context

import { chromium } from 'playwright';

const browser = await chromium.launch();
const context = await browser.newContext({
  storageState: 'playwright/.auth/account-a.json'
});
const page = await context.newPage();
await page.goto('https://example.com/account');
console.log(await page.locator('h1').textContent());
await browser.close();

This approach starts each browser context with the same known authentication inputs while leaving unrelated history, tabs and extensions behind. It is usually preferable for parallel tests, provided every worker gets an appropriate state file or an isolated copy.

Handle sessionStorage separately

storageState does not automatically persist sessionStorage, and sessionStorage is scoped to a particular origin and browser tab. If an application keeps a token there, save it with code running in that origin and inject it before the application loads on the next run. Keep the serialized value in a secret store or protected file, not in source control.

// Capture after login, while the page is on the application's origin.
const sessionValue = await page.evaluate(() => sessionStorage.getItem('app-token'));
// Persist sessionValue securely, then restore it before navigation:
await context.addInitScript(value => {
  sessionStorage.setItem('app-token', value);
}, sessionValue);

The exact key and serialization are application-specific. If the site rotates the token or binds it to a tab, replaying it may fail; in that case, perform a fresh login or use the site’s supported test account flow.

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

Keep accounts and jobs isolated

Separate persistent profiles

Use one user-data directory per account, tenant or concurrent job. This isolates cookies and local storage and avoids the single-owner conflict. Give each directory a documented browser channel, path and retention policy so an operator knows what can be deleted safely.

Use isolated contexts for clean tests

Within one browser process, a new context gives a clean test boundary without writing a long-lived profile. It is the better default for tests that must start logged out or must not inherit another test’s cache and cookies.

Understand CLI and MCP profiles

The Playwright CLI keeps cookies and storage between commands when you use its persistent mode; its default in-memory mode loses the profile when the browser closes. Named CLI sessions keep cookies, localStorage, IndexedDB, cache, history, tabs and console logs separate from one another.

Playwright MCP uses persistent profiles by default. It accepts an explicit --user-data-dir and also offers isolated mode and saved storage-state files. The same one-browser-per-profile rule applies, so parallel MCP jobs require separate directories.

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

Firefox profiles and containers are different boundaries

Firefox profiles are complete data boundaries: bookmarks, passwords, settings, add-ons, browsing history, cookies and logins are separated between profiles. Containers are narrower partitions inside one profile, primarily separating browsing data such as cookies and logins.

Firefox’s Total Cookie Protection creates a site-isolated cookie jar, while Enhanced Tracking Protection blocks trackers. Those privacy controls can change cross-site behavior. Test persistence and privacy partitioning independently: a login that works in an unrestricted profile may not behave identically when third-party storage is partitioned or blocked.

Protect persistent state like credentials

Playwright’s authentication documentation warns: “The browser state file may contain sensitive cookies and headers that could be used to impersonate you or your test account.” A persistent directory has the same practical risk.

  • Add profile and auth-state paths to .gitignore and prevent them from entering build artifacts or support bundles.
  • Restrict filesystem permissions to the account running automation.
  • Use dedicated, low-privilege test accounts rather than personal administrator accounts.
  • Delete or rotate state when an account, runner or repository may have been exposed.
  • Document browser version/channel, profile path, owner and retention period.
  • Do not copy a profile between unrelated users or machines without reviewing its cookies, extensions and encryption behavior.

Reliability, performance and cost considerations

A persistent profile avoids repeating interactive login and can retain expensive setup such as IndexedDB data, but it also accumulates cache, history, extensions and stale tokens. Periodically create a fresh profile and re-authenticate when a workflow becomes flaky. Keep the profile on fast local storage in CI, and avoid network filesystems that can mishandle locks.

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

Saved storageState files are smaller and easier to reproduce than full profiles, but they represent only the layers Playwright serializes. They do not automatically include sessionStorage, and they may become invalid when the service revokes or rotates credentials. Persistence reduces setup time; it does not guarantee a session will never expire.

Troubleshooting persistent sessions

Symptom Likely cause Fix
Every run shows the login page Wrong directory, a new temporary path, expired cookies or a login stored in sessionStorage Log the absolute path, confirm the same profile is used, re-authenticate, and implement sessionStorage capture if the application requires it.
“Profile is already in use” or a launch lock error Another browser process owns the directory Close the first process or assign a separate directory; never delete a lock while the owner is still running.
Parallel jobs log into one another’s accounts Workers share a profile or auth-state file Provision one directory or state file per account and enforce ownership in the job runner.
State file works locally but not in CI Different browser channel, origin, filesystem permissions or revoked credentials Use the same browser channel, copy the file through a secret mechanism, verify permissions and regenerate state on the CI runner.
Cross-site login or embedded content fails Firefox cookie partitioning or tracking protection changes storage behavior Test with the intended privacy settings and avoid assuming third-party cookies are available.
Profile becomes slow or flaky Accumulated cache, history, extensions or corrupted state Close cleanly, remove unnecessary extensions, archive the old directory and start a fresh dedicated profile.
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 image or PDF of a page rather than an interactive, logged-in browser workflow, ScreenshotNeo returns the capture from one GET request. Before capture it accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing result.

Use the ScreenshotNeo API documentation for all options. A basic request is:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo also supports full-page captures with lazy images loaded, CSS-element shots, dark mode, 12 device presets and custom viewports, retina scale, PDF paper size/margins/landscape/page ranges, HTML/CSS-to-image, custom JavaScript and CSS, clicks before capture, selector hiding, waits for selectors/delays/network idle, ad/tracker/request/resource blocking, custom headers/cookies/user agents/Authorization, timezone and geolocation, transparent backgrounds, resizing, TTL-based caching, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API and an OpenAPI specification. Parameter names used by other screenshot APIs also work for easier migration.

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

The MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients. Plans include 1,000 screenshots per month free with no card, Starter at $5 for 3,000, Growth at $15 for 15,000, Pro at $39 for 60,000, Scale at $99 for 250,000 and Business at $249 for 1,000,000; yearly billing gives two months free, and every feature is on every plan. Create a free ScreenshotNeo account to start with the 1,000 no-card screenshots.

Frequently Asked Questions

Can a persistent profile be shared safely between a laptop and CI?

Treat a profile as machine- and account-specific state. Prefer generating a controlled storageState file or logging in again on the CI runner instead of copying a personal profile.

Does closing a page sign the user out?

No. Closing a page normally leaves cookies and other persistent data in the profile; signing out is an application action that may revoke or remove that state.

When should I delete a profile instead of repairing it?

Delete and recreate it when ownership is uncertain, credentials may have leaked, the profile is corrupted, or repeated cleanup cannot explain flaky behavior.

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

Are containers equivalent to separate Firefox profiles?

No. Profiles separate Firefox’s complete data set, while containers provide a narrower partition inside one profile.

The Bottom Line

For durable Playwright logins, use one dedicated persistent directory per account and one browser owner per directory. Choose storageState for repeatable, clean test contexts, handle sessionStorage explicitly, and protect every saved cookie or header as a credential.

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
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

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.