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

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Playwright does not restore sessionStorage through its normal storageState file. Read the JSON in your test process, then register a BrowserContext.addInitScript callback that writes the entries into window.sessionStorage before application scripts run. Scope the callback to the intended origin and convert every value to a string.

The documented approach

Playwright’s authentication guide documents an init-script workaround because its reusable storage state covers cookies, local storage, IndexedDB and WebAuthn passkeys, but not session storage. The sequence is:

  1. Save or receive a JSON object containing the session-storage entries.
  2. Parse that object in Node.js, outside the browser.
  3. Create a browser context.
  4. Call context.addInitScript() before opening or navigating pages that need the data.
  5. Write each entry with sessionStorage.setItem() when the page belongs to the target origin.

See the official guidance in Playwright Authentication and the execution details in the BrowserContext API.

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

Complete TypeScript example

Assume playwright/.auth/session.json contains a JSON object such as {"cartId":"abc123","onboarding":"complete"}. The following script loads it and seeds pages on example.com:

#1 Best Overall
Sale
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
  • Easily store and access 2TB to content on the go with the Seagate Portable Drive, a USB external hard drive
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.
import fs from 'node:fs';
import { chromium } from 'playwright';

const sessionStorage = JSON.parse(
  fs.readFileSync('playwright/.auth/session.json', 'utf-8'),
);

const browser = await chromium.launch();
const context = await browser.newContext();

await context.addInitScript((storage) => {
  if (window.location.hostname !== 'example.com') return;

  for (const [key, value] of Object.entries(storage)) {
    window.sessionStorage.setItem(key, String(value));
  }
}, sessionStorage);

const page = await context.newPage();
await page.goto('https://example.com/');

console.log(await page.evaluate(() => ({
  cartId: sessionStorage.getItem('cartId'),
  onboarding: sessionStorage.getItem('onboarding'),
})));

await browser.close();

Replace the hostname and file path with your application’s values. The callback runs after a document is created but before that document’s own scripts execute, so a single-page application can read the seeded values during startup. Register it before newPage() and before any navigation that depends on the data.

Origin, scheme, port and frame scope

Web Storage is origin-scoped. The origin includes the scheme, hostname and port: https://app.example.com, http://app.example.com and https://app.example.com:8443 are different origins. A hostname-only check is suitable for the simple official example, but use a stricter guard when your test visits multiple environments:

await context.addInitScript((storage) => {
  const allowed = new Set([
    'https://app.example.com',
    'https://app.example.com:8443',
  ]);
  if (!allowed.has(window.location.origin)) return;

  for (const [key, value] of Object.entries(storage)) {
    window.sessionStorage.setItem(key, String(value));
  }
}, sessionStorage);

addInitScript applies to pages in the context, including later navigations. It can also execute in child frames. That is useful when the target application stores data in a same-origin iframe, but it means the guard is important: without one, unrelated pages or frames in the context could receive the same values.

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

JSON types and storage semantics

The Web Storage API stores strings. Calling String(value) makes numbers and booleans usable, but it turns an object into [object Object] and an array into a comma-separated string. Serialize structured values deliberately:

await context.addInitScript((storage) => {
  if (window.location.origin !== 'https://example.com') return;

  for (const [key, value] of Object.entries(storage)) {
    const encoded = typeof value === 'string'
      ? value
      : JSON.stringify(value);
    window.sessionStorage.setItem(key, encoded);
  }
}, sessionStorage);

On the application side, parse values that were encoded as JSON:

Rank #2
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
  • Easily store and access 1TB to content on the go with the Seagate Portable Drive, a USB external hard drive.Specific uses: Personal
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop. Reformatting may be required for Mac
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.
const preferences = JSON.parse(
  sessionStorage.getItem('preferences') ?? '{}',
);

If the file is meant to be a direct snapshot, save strings in it and avoid ambiguity. Validate the parsed result before passing it to the page:

if (!sessionStorage || typeof sessionStorage !== 'object' || Array.isArray(sessionStorage)) {
  throw new Error('Session storage JSON must be an object');
}

Creating a session-storage JSON file

The authentication guide shows how to extract the current page’s values by serializing the browser’s storage, then parse that file when creating a new context:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const json = await page.evaluate(() => JSON.stringify(sessionStorage));
fs.writeFileSync('playwright/.auth/session.json', json, 'utf8');

Run the extraction on the same origin as the values you need. Session storage belongs to that origin and browser context; a file collected from one host does not automatically apply to another host.

Using Playwright Test fixtures

With Playwright Test, install the init script on the supplied context fixture before the test navigates. The runner’s storageState option can continue to provide cookies and other supported state independently.

import { test as base, expect } from '@playwright/test';
import fs from 'node:fs';

const sessionStorage = JSON.parse(
  fs.readFileSync('playwright/.auth/session.json', 'utf8'),
);

export const test = base.extend({
  context: async ({ context }, use) => {
    await context.addInitScript((storage) => {
      if (window.location.origin !== 'https://example.com') return;
      for (const [key, value] of Object.entries(storage)) {
        window.sessionStorage.setItem(key, String(value));
      }
    }, sessionStorage);
    await use(context);
  },
});

export { expect };

Use the extended fixture in a test:

import { test, expect } from './fixtures';

test('opens the prepared account page', async ({ page }) => {
  await page.goto('https://example.com/account');
  await expect(page).toHaveURL(/account/);
});

If you configure storageState in playwright.config.ts, remember that it does not replace this script for session storage. The supported test-runner option is described in the TestOptions API.

Rank #3
Kosbees 500 GB External Hard Drives,Portable Hard Drive for Windows,Ultra Slim External HDD Store Compatible with PC, MAC,Laptop,PS4, Xbox one, Xbox 360;Plug and Play Ready
  • 【Plug-and-Play Expandability】 With no software to install, just plug it in and the drive is ready to use in Windows(For Mac,first format the drive and select the ExFat format.
  • 【Fast Data Transfers 】The external hard drives with the USB 3.0 cable to provide super fast transfer speed. The theoretical read speed is as high as 110MB/s-133MB/s, and the write speed is as high as 103MB/s.
  • 【High capacity in a small enclosure 】The small, lightweight design offers up to 500GB capacity, offering ample space for storing large files, multimedia content, and backups with ease. Weighing only 0.35 Lbs, it's easy to carry "
  • 【Wide Compatibility】Supports PS4 5/xbox one/Windows/Linux/Mac and other operating systems, ensuring seamless integration with game consoles,various laptops and desktops .
  • Important Notes for PS/Xbox Gaming Devices: You can play last-gen games (PS4 / Xbox One) directly from an external hard drive. However, to play current-gen games (PS5 / Xbox Series X|S), you must copy them to the console's internal SSD first. The external drive is great for keeping your library on hand, but it can't run the new games.

Authentication and security

Session storage can contain bearer tokens, temporary credentials or identifiers that impersonate a user. Playwright warns that saved authentication state may contain sensitive cookies and headers; protect a session JSON file with the same care.

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.
  • Keep it outside source control and add the directory to .gitignore.
  • Use filesystem permissions and CI secret storage appropriate for the account.
  • Prefer a test account with limited privileges.
  • Delete generated files when a run or debugging session ends.
  • Never print token values in test logs or failure diagnostics.

Do not assume session storage is the actual login mechanism. Inspect the application: authentication may instead use cookies, local storage, IndexedDB or a server-side session. Use Playwright’s normal storageState flow for the supported stores and add this workaround only for the session-storage portion.

Common failures and fixes

The application still behaves as logged out

Check that the script was registered before newPage() or navigation, and that the URL’s exact origin passes your guard. Also verify that the application reads session storage rather than a cookie or another store.

Values appear as the wrong type

Storage always returns strings. If the application expects an object, write it with JSON.stringify and read it with JSON.parse. Do not rely on JavaScript’s default conversion for arrays or objects.

The script seeds an unintended site

Replace a broad hostname check with an explicit set of origins. Include the correct HTTPS scheme, subdomain and non-default port, and retain the guard for child frames.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
YOTUO 1TB External Hard Drive, Portable Storage Expansion HDD, USB 3.0 & USB-C for PC, Mac, Desktop, Laptop, Smartphone, PS4, Xbox One, Xbox 360, Office & Game, Black
  • 【Versatile Storage Expansion – For Gaming, Work & Everyday Use】 Running out of space on your PS5 or Xbox Series X/S? This external hard drive lets you store and play PS4 / Xbox One games directly, instantly freeing up your console’s internal storage for next‑gen titles. At the same time, it handles work file backups, media libraries, and cross‑device data transfers with ease. One drive, all your needs. *(Note: PS5 / Xbox Series X|S games cannot be run or stored directly from the external hard drive. However, by offloading your PS4 / Xbox One games, you can free up valuable space for newer titles.)*
  • 【Patented Silicone Sleeve – Data Protection You Can Count On】 Worried about drops? We’ve got you covered. The patented built‑in silicone sleeve acts like a shock‑absorbing armor, cushioning your drive against bumps and falls. Whether it’s important work documents, precious family photos, or hard‑earned game saves, your data deserves this level of protection.
  • 【Plug & Play, Compatible with Computers & Consoles】 No complicated setup—just plug in and go. Works seamlessly with Windows, Mac, and Linux computers, as well as PS4, PS5, Xbox One, and Xbox Series X/S. Process files at the office, back up data at home, or enjoy gaming in your downtime—one drive handles all your devices, simply and hassle‑free.
  • 【USB 3.0 Ultra‑Fast Transfer – No More Waiting】 Tired of watching progress bars crawl? With USB 3.0 speeds up to 5Gbps, large files transfer in seconds. Whether you’re moving work documents, transferring hundreds of gigs of games, or backing up a year’s worth of photos, you get more done in less time.
  • 【Sleek, Lightweight, and Ready to Go】 Weighing just 0.16 kg—lighter than a can of soda—this compact drive features a stylish mirror‑and‑frosted finish. Toss it in your bag and go, whether you’re heading to the office, visiting a friend for a gaming session, or giving a presentation on the road.

A page opened before the callback was installed

Init scripts affect future document creation and navigations. Install the callback immediately after creating the context. For an already loaded page, set the values with page.evaluate and reload if the application only reads them during startup.

The JSON file cannot be parsed

Ensure it is UTF-8 JSON containing one object, not a JavaScript module, comments or a copied browser-export wrapper. Log only the keys while debugging, never secrets.

State leaks between tests

Use a fresh context per test or clear the relevant keys. A context shares its storage among pages of the same origin, so reusing one context can intentionally or accidentally carry values forward.

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

Version notes and adjacent APIs

The documented workaround remains relevant even as Playwright adds storage APIs. The current references list BrowserContext.setStorageState in v1.59, Web Storage APIs in v1.61, IndexedDB capture in v1.51, WebAuthn credential capture in v1.61 and OPFS capture in v1.63. Check the version installed in your project before using those adjacent features; none makes the init-script method unnecessary for a JSON session-storage seed.

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

The Web Storage reference covers page access to local and session storage: Playwright WebStorage API.

Best Value
Sale
Aiolo Innovation 500GB External Hard Drive Ultra Slim Portable HDD-USB 3.0 for PC, Mac, Laptop, PS4, Xbox one,Xbox 360 HD-A4
  • Ultra fast data transfers: the external hard drive works with USB 3.0 thickened copper cable to provide super fast transfer speeds. Theoretical read speed is as high as 110MB/s-133MB/s and write speed is as high as 103MB/s.
  • Ultra-thin and quiet: the motherboard adopts a noise-free solution, giving you a quiet working environment. Lightweight and portable size designed to fit in your pocket for easy portability.
  • Compatibility: compatible with PS4/xbox one/Windows/Linux/Mac/Android,Stable and fast downloading on game console no difference from fast transmission when using on PC.
  • Plug and Play: no software to install, just plug it in and the drive is ready to use. The hard drive chip is wrapped with aluminum anti-interference layer to increase heat dissipation and protect data
  • Package Contents: 1* portable hard drive, 1 *USB 3.0 cable, 1*USB to type C adapter,1 *user manual, shell packaging, three-year manufacturer's warranty and free technical support services

Performance and reliability considerations

  • Parsing a small JSON object in the test process is inexpensive; avoid putting large application caches into every context.
  • Seed only the keys required for the scenario, which reduces accidental coupling to expired data.
  • Use deterministic fixture files for repeatable tests, and regenerate them when the application changes its storage schema.
  • When tests run in parallel, give workers independent files or accounts if values represent mutable user state.
  • Keep the init callback synchronous and simple. Network calls or asynchronous setup belong in the test fixture, not in the storage-writing loop.

Or skip the browser setup

If your goal is simply to obtain clean page images or PDFs rather than exercise a stateful browser test, ScreenshotNeo provides a website screenshot API and MCP server. A single request can return PNG, JPEG, WebP or PDF, with options for full-page capture, device and retina settings, custom JavaScript and CSS, selectors, waits, headers, cookies and more. Its cleanup step accepts consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets before capture. Failed loads, blank pages, bot checks, CAPTCHAs and cache hits are not billed, and response headers identify the page verdict and billing result.

After creating an API key, the basic call is:

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 complete parameter reference in the ScreenshotNeo documentation. An MCP server exposes take_screenshot, get_page_info and capture_pdf to 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. Create a free ScreenshotNeo account.

FAQ

Can I put session storage directly in storageState?

No. Use an init script to write the values before page scripts execute; storageState does not persist sessionStorage.

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

Does this work for every frame?

The init script can run in child frames, but your origin guard must permit the frame’s actual origin.

Should I store tokens in a repository for CI?

No. Treat the JSON as authentication material, keep it out of source control and provide it through protected CI storage.

Frequently Asked Questions

Can I put session storage directly in storageState?

No. Use an init script to write the values before page scripts execute; storageState does not persist sessionStorage.

Does this work for every frame?

The init script can run in child frames, but your origin guard must permit the frame’s actual origin.

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

Should I store tokens in a repository for CI?

No. Treat the JSON as authentication material, keep it out of source control and provide it through protected CI storage.

Quick Recap

SaleBestseller No. 1
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$129.99
Bestseller No. 2
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$119.80

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.