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

Use one of three supported Playwright patterns to run Headless Chrome with an authenticated session: launch a dedicated persistent profile, save and restore a storageState file, or attach to an already-running Chromium process over CDP. Use a persistent profile for continuity, storageState for repeatable isolated runs, and CDP when the live browser already owns the session. Do not point automation at the Chrome profile you use for normal browsing.

Choose the session-sharing method

Headless mode does not remove cookies or local storage. It changes how the browser is displayed. The important decision is where the authenticated browser state lives and whether your script creates or joins the browser process.

Method What happens Best fit Main caution
Persistent context Playwright creates Chromium with a specified user-data directory and keeps its cookies, local storage and other profile data. Long-lived automation that should stay signed in between runs. Use a separate automation directory; Chrome profile locking prevents safe concurrent ownership.
storageState An interactive login exports authentication state to JSON. Later contexts import that file. CI, test projects and reproducible, isolated runs. The file is a credential. Protect it, rotate it and regenerate it after expiry.
CDP attachment Playwright connects to an existing Chromium instance through its remote debugging endpoint. A human or another process already has the required tabs and live session. Anyone who can reach the endpoint can control the logged-in browser.

Prerequisites and a safe directory layout

  • Install a current Playwright package and its Chromium browser.
  • Create directories owned by the automation account, such as browser-data/ and playwright/.auth/.
  • Keep both directories outside version control. Add the authentication directory and any profile directory to .gitignore.
  • Use one profile or state file per account when jobs run for different users.

Authentication can include cookies, local storage, IndexedDB, origin private file-system data and virtual WebAuthn credentials. Which items are needed depends on the site. A login token in IndexedDB, for example, will not be replaced by copying only cookies.

Pattern 1: launch a dedicated persistent profile

launchPersistentContext(userDataDir) starts Chromium with a profile directory that survives process shutdown. Log in once with a visible browser, then run the same directory headlessly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Log in once

import { chromium } from 'playwright';

const context = await chromium.launchPersistentContext('./browser-data/account-a', {
  headless: false,
});
const page = await context.newPage();
await page.goto('https://your-app.example/login', { waitUntil: 'domcontentloaded' });
console.log('Complete the login and MFA in the opened browser. Press Enter here when finished.');
process.stdin.once('data', async () => {
  await context.close();
  process.exit(0);
});

Wait until redirects finish and the application has written its cookies and origin data. Complete any multi-factor step in this interactive run rather than trying to bypass it.

Reuse the profile headlessly

import { chromium } from 'playwright';

const context = await chromium.launchPersistentContext('./browser-data/account-a', {
  headless: true,
  viewport: { width: 1440, height: 900 },
});
try {
  const page = context.pages()[0] || await context.newPage();
  await page.goto('https://your-app.example/dashboard', {
    waitUntil: 'domcontentloaded',
    timeout: 60_000,
  });
  await page.waitForLoadState('networkidle');
  await page.screenshot({ path: 'dashboard.png', fullPage: true });
} finally {
  await context.close();
}

Do not use the normal Chrome “User Data” directory. Playwright warns that doing so can leave pages unloaded or cause the browser to exit. Browsers also prevent multiple instances from launching with the same user-data directory, so serialize jobs that use one profile or assign each job its own directory.

Pattern 2: save and restore Playwright storageState

This pattern separates the one-time login from every later run. It is usually easier to reproduce in clean contexts and in CI.

Export 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://your-app.example/login', { waitUntil: 'domcontentloaded' });
console.log('Finish login and MFA, then press Enter.');
process.stdin.once('data', async () => {
  await context.storageState({
    path: 'playwright/.auth/user.json',
    indexedDB: true,
  });
  await browser.close();
  process.exit(0);
});

Use the indexedDB option when the application stores authentication data there. Storage-state snapshots can also include origin data and supported virtual WebAuthn credentials; use the options documented by the Playwright version installed in your project.

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

Start an isolated authenticated context

import { chromium } from 'playwright';

const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({
  storageState: 'playwright/.auth/user.json',
});
try {
  const page = await context.newPage();
  await page.goto('https://your-app.example/dashboard', {
    waitUntil: 'domcontentloaded',
    timeout: 60_000,
  });
  await page.screenshot({ path: 'dashboard.png', fullPage: true });
} finally {
  await context.close();
  await browser.close();
}

Regenerate the file when the session expires. Treat it like a password: cookies and headers inside it can impersonate the account. Restrict filesystem permissions, never commit it, and remove old copies from CI artifacts and logs.

When the site uses sessionStorage

sessionStorage is tied to a page and is not persisted by Playwright’s storage-state API. Serialize it in the logged-in page, then install it before application scripts run.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
// Run while the page is authenticated
const sessionStorageData = await page.evaluate(() => {
  const data = {};
  for (let i = 0; i < sessionStorage.length; i++) {
    const key = sessionStorage.key(i);
    data[key] = sessionStorage.getItem(key);
  }
  return data;
});
// Save sessionStorageData as a protected JSON file.

// In the later run, before navigation:
await context.addInitScript(({ origin, data }) => {
  if (location.origin === origin) {
    for (const [key, value] of Object.entries(data)) {
      sessionStorage.setItem(key, value);
    }
  }
}, { origin: 'https://your-app.example', data: sessionStorageData });

Install the init script before page.goto; otherwise the application may read an empty session and redirect to login.

Pattern 3: attach to an existing Chromium browser with CDP

CDP is useful when the desired profile and tabs already belong to a running Chromium process. Start that process with a protected debugging endpoint and a dedicated user-data directory.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
google-chrome 
  --headless=false 
  --remote-debugging-address=127.0.0.1 
  --remote-debugging-port=9222 
  --user-data-dir="$HOME/browser-data/cdp-account"

Complete the login in that browser. Then connect from Playwright:

import { chromium } from 'playwright';

const browser = await chromium.connectOverCDP('http://127.0.0.1:9222');
const contexts = browser.contexts();
if (!contexts.length) throw new Error('No browser context is available');
const context = contexts[0];
const page = context.pages()[0] || await context.newPage();
await page.goto('https://your-app.example/dashboard', {
  waitUntil: 'domcontentloaded',
  timeout: 60_000,
});
await page.screenshot({ path: 'attached-dashboard.png', fullPage: true });
await browser.close();

Closing the Playwright connection may close the browser depending on the connection and process lifecycle, so decide which process owns shutdown before using this in a service. CDP attachment is supported for Chromium-based browsers; it is not a general Firefox or WebKit connection method.

Capture only after authentication is confirmed

A successful navigation does not prove that the session is valid. Check a page-specific selector or URL before collecting data or images.

await page.waitForURL('**/dashboard');
await page.locator('[data-testid="account-menu"]').waitFor({ state: 'visible', timeout: 30_000 });
const loginFormVisible = await page.locator('form[action*="login"]').isVisible().catch(() => false);
if (loginFormVisible) throw new Error('Session expired or authentication was rejected');

Prefer a stable application marker over a title string. Also wait for the content that must be captured; domcontentloaded only means the initial document was parsed, while images and client-rendered data may still be loading.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Or skip the browser setup

If your goal is a clean screenshot rather than controlling a logged-in browser, ScreenshotNeo returns an image or PDF from one request. It can accept custom headers, cookies or an Authorization value for services that expose those credentials, while browser-session reuse remains your responsibility.

For the complete parameter list, see the ScreenshotNeo API documentation.

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}`);

Before capture, ScreenshotNeo 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 or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and whether it was billed. Its MCP server provides take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients. The free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 shots. Sign up for the free ScreenshotNeo plan.

Security checklist for authenticated automation

  • Use a dedicated persistent profile or a short-lived state file, never your everyday Chrome profile.
  • Keep auth JSON, cookies, bearer headers and passkey-related credentials out of source control, logs, screenshots and build artifacts.
  • Set restrictive directory permissions and delete expired or unused state.
  • Bind the CDP endpoint to a protected interface such as 127.0.0.1; do not expose port 9222 to the public internet.
  • Separate profiles or state files for separate accounts and environments.
  • Use a secret manager for API keys and credentials rather than embedding them in scripts.

Troubleshooting common failures

The page redirects to login

The state may have expired, the login was saved before redirects completed, or the application stores its token in IndexedDB or sessionStorage. Re-run the interactive login, save state only after the final authenticated page appears, enable IndexedDB capture when needed, and apply the sessionStorage init script before navigation.

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

Chromium exits or pages never load

Another process may own the same user-data directory, or the script may be using your regular Chrome directory. Stop the competing process and switch to a new automation directory. Do not launch two jobs against one persistent profile simultaneously.

CDP reports a connection error

Confirm that Chromium was started with the debugging port, that the address is reachable from the Playwright process, and that a firewall or container network is not blocking it. Keep the endpoint local and use the exact port exposed by the browser process.

The screenshot is blank or incomplete

Wait for a stable selector, client-rendered content or network idle instead of relying only on the first navigation event. For lazy-loaded pages, scroll or use the site’s own loading trigger before calling screenshot.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Two accounts appear to share data

They are probably using the same profile directory or state file. Assign a unique directory or JSON file to each account and clear any previously copied artifacts before rerunning.

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

MFA succeeds manually but fails in CI

Export the state after completing MFA in an interactive, trusted environment, then deliver the protected state file to CI through its secret mechanism. Do not attempt to automate or weaken the second factor merely to make a headless job pass.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability and cost considerations

Startup and reuse

A persistent context avoids repeating login work, while a fresh context loaded from storageState gives stronger isolation between tests. Reuse a browser process for a batch of pages, but create separate contexts when jobs need independent cookies or local storage.

Parallel jobs

Parallelize with separate state files or profile directories. Sharing one profile introduces file locks and cross-test mutations; sharing one state file can also produce account mix-ups if a job refreshes or overwrites it.

Network waits

Set explicit navigation and selector timeouts appropriate to your application. A blanket long timeout hides genuine outages, while an overly short timeout misclassifies slow authentication redirects. Record the final URL and a small diagnostic screenshot when a run fails, but ensure diagnostics cannot expose secrets.

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

Operational cost

Playwright and Chromium consume compute, memory and storage on the machine that runs them; the documentation does not establish a universal latency or success-rate benchmark. ScreenshotNeo charges only for clean shots and offers 1,000 free shots monthly, with paid plans beginning at $5 for 3,000 shots, which can be simpler when you need rendered images rather than browser control.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

FAQ

Can I move a saved state file between operating systems?

Cookies and origin data are generally portable, but browser versions, encryption facilities, filesystem paths and hardware-backed credentials can affect portability. Validate the state in the same browser family and regenerate it when a site rejects it.

How do I know whether a session is still valid without opening a dashboard?

Call a lightweight authenticated endpoint or load a page that has a deterministic signed-in marker, then treat an unexpected login redirect or unauthorized response as an expired session.

Should a service keep one browser open permanently?

Only when the live session and CDP ownership are operational requirements. Otherwise, short-lived contexts loaded from protected state are easier to isolate, restart and rotate.

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

Frequently Asked Questions

Can I use the same authenticated state for multiple websites?

Only if the state was created for those sites and their origins; storage state is origin-scoped, so a file from one service does not authenticate an unrelated domain.

What should I rotate after a suspected credential leak?

Invalidate the account sessions or tokens at the service, delete every affected profile and state copy, issue new credentials, and recreate the automation state from a trusted login.

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.