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

In both Puppeteer and Playwright, a BrowserContext is the boundary for a browser session: pages in one context share its cookies and other site storage, while separate contexts keep sessions isolated. Create a context for each identity or test that needs separation, save and restore Playwright authentication state when you need a reusable signed-in session, and close the context when the work is done.

What counts as a browser session?

A session is more than a tab. The browser context owns the state that makes pages behave like a particular user: cookies and, depending on the application and framework, local storage and other origin-specific data. Pages and popups belong to a context. Put pages that should share an identity in the same context; use different contexts for separate identities or isolated tests.

Puppeteer and Playwright both use BrowserContext for this boundary. Playwright describes its contexts as independent, incognito-like profiles; its non-persistent contexts do not write browsing data to disk. In Playwright Test, the runner creates a fresh context for each test by default, which helps prevent one test’s state from carrying into another. See the Playwright isolation guide, Playwright pages guide, and Puppeteer BrowserContext API.

Create, use, and close a session

For a temporary session, create a context, open pages from it, do the work, then close the context. Closing a context closes its pages. The default browser context cannot be closed; create a separate context when you need an independently managed session.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Logitech M185 Compact Ambidextrous 2.4 GHz Wireless Mouse - Swift Grey
  • Compact Mouse: With a comfortable and contoured shape, this Logitech ambidextrous wireless mouse feels great in either right or left hand and is far superior to a touchpad
  • Durable and Reliable: This USB wireless mouse features a line-by-line scroll wheel, up to 1 year of battery life (2) thanks to a smart sleep mode function, and comes with the included AA battery
  • Universal Compatibility: Your Logitech mouse works with your Windows PC, Mac, or laptop, so no matter what type of computer you own today or buy tomorrow your mouse will be compatible
  • Plug and Play Simplicity: Just plug in the tiny nano USB receiver and start working in seconds with a strong, reliable connection to your wireless computer mouse up to 33 feet / 10 m (5)
  • Better than touchpad: Get more done by adding M185 to your laptop; according to a recent study, laptop users who chose this mouse over a touchpad were 50% more productive (3) and worked 30% faster (4)

Playwright

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  try {
    const context = await browser.newContext();
    try {
      const page = await context.newPage();
      await page.goto('https://example.com');
      // Perform work in this session.
    } finally {
      await context.close();
    }
  } finally {
    await browser.close();
  }
})();

Puppeteer

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  try {
    const context = await browser.createBrowserContext();
    try {
      const page = await context.newPage();
      await page.goto('https://example.com');
      // Perform work in this session.
    } finally {
      await context.close();
    }
  } finally {
    await browser.close();
  }
})();

Use context-level operations for state shared by the session rather than treating one page as the session. The exact APIs available can vary by installed version; check the documentation for your package version before using newer methods.

Save and reuse a signed-in Playwright session

Playwright’s authentication guide recommends signing in once, saving the context’s storage state, and using that state when creating contexts for later tests. This avoids repeating interactive login steps, but the saved file is sensitive: it can contain cookies or headers that let someone impersonate the account. Keep it out of source control and logs, use a suitably limited test account, and restrict access to the file. Playwright strongly discourages checking authentication state into public or private repositories. See the Playwright authentication guide.

Rank #2
Sale
Logitech G305 Lightspeed Wireless Gaming Mouse - Black
  • The next-generation optical HERO sensor delivers incredible performance and up to 10x the power efficiency over previous generations, with 400 IPS precision and up to 12,000 DPI sensitivity
  • Ultra-fast LIGHTSPEED wireless technology gives you a lag-free gaming experience, delivering incredible responsiveness and reliability with 1 ms report rate for competition-level performance
  • G305 wireless mouse boasts an incredible 250 hours of continuous gameplay on just 1 AA battery; switch to Endurance mode via Logitech G HUB software and extend battery life up to 9 months
  • Wireless does not have to mean heavy, G305 lightweight mouse provides high maneuverability coming in at only 3.4 oz thanks to efficient lightweight mechanical design and ultra-efficient battery usage
  • The durable, compact design with built-in nano receiver storage makes G305 not just a great portable desktop mouse, but also a great laptop travel companion, use with a gaming laptop and play anywhere

Capture state

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();

  await page.goto('https://example.com/login');
  // Complete the application's login flow here.
  await page.context().storageState({ path: 'playwright/.auth/user.json' });

  await browser.close();
})();

Create the playwright/.auth directory before running this script and add it to .gitignore. The login steps are application-specific; do not assume that visiting a login page alone signs in.

Load state into a new context

const context = await browser.newContext({
  storageState: 'playwright/.auth/user.json'
});
const page = await context.newPage();
await page.goto('https://example.com/account');

The saved state is useful only to the extent that it captures the authentication mechanism your app uses. Playwright’s standard workflow covers cookies and local storage. The current API also documents options for capturing IndexedDB; use the relevant option if your app stores authentication data there, and verify support against your installed Playwright version. The API reference also documents other version-dependent storage-state capabilities, including virtual WebAuthn credentials. Do not assume that a cookie file alone restores every application’s login.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Logitech M185 Compact Ambidextrous Wireless Mouse with Rubber Grips - Blue
  • Compact Mouse: With a comfortable and contoured shape, this Logitech ambidextrous wireless mouse feels great in either right or left hand and is far superior to a touchpad
  • Durable and Reliable: This USB wireless mouse features a line-by-line scroll wheel, up to 1 year of battery life (2) thanks to a smart sleep mode function, and comes with the included AA battery
  • Universal Compatibility: Your Logitech mouse works with your Windows PC, Mac, or laptop, so no matter what type of computer you own today or buy tomorrow your mouse will be compatible
  • Plug and Play Simplicity: Just plug in the tiny nano USB receiver and start working in seconds with a strong, reliable connection to your wireless computer mouse up to 33 feet / 10 m (5)
  • Better than touchpad: Get more done by adding M185 to your laptop; according to a recent study, laptop users who chose this mouse over a touchpad were 50% more productive (3) and worked 30% faster (4)

Handle sessionStorage separately

Playwright’s normal storage-state workflow does not persist sessionStorage. If the application depends on it, read the needed values from an authenticated page and initialize them in a new context before the application scripts execute. Scope restoration to the intended host (or, where appropriate, exact origin) so secrets are not injected into unrelated sites. Session storage has page-session behavior, so restoring values is an application-specific workaround, not a general replacement for the browser’s original session lifecycle.

// Capture only the values the application needs, and protect them like credentials.
const savedSessionStorage = await page.evaluate(() => {
  const values = {};
  for (let i = 0; i < sessionStorage.length; i++) {
    const key = sessionStorage.key(i);
    values[key] = sessionStorage.getItem(key);
  }
  return values;
});

// For a new context, install this before navigating to the application.
await context.addInitScript(({ hostname, values }) => {
  if (window.location.hostname !== hostname) return;
  for (const [key, value] of Object.entries(values)) {
    window.sessionStorage.setItem(key, value);
  }
}, { hostname: 'example.com', values: savedSessionStorage });

Do not serialize and restore all storage blindly if the application stores unrelated or short-lived values there. Select the keys required for the test, and ensure the initialization runs before the page’s application code.

Rank #4
Sale
Amazon Basics 3-Button USB Wired Mouse with Responsive Tracking, Plug & Play, Compatible with Windows and Mac, Black
  • Computer mouse for easily navigating a computer interface; click, scroll, and more
  • USB-A wired connection; if existing device only supports USB-C, an additional adapter will be required
  • High-definition (1000 dpi) optical tracking ensures responsive cursor control for precise tracking and easy text selection
  • 3 buttons offer effortless fingertip control
  • Plug-and-go ready for instant use

Read, add, and clear cookies

Cookie methods are context-scoped in both frameworks. Playwright provides cookies(), addCookies(), and clearCookies(); cookie input can identify scope using a URL or a domain-and-path pair and can include attributes such as expiry, httpOnly, secure, sameSite, and partition keys. Puppeteer documents context-level cookie retrieval, setting, deletion, and matching-cookie deletion. Use the current framework reference for accepted argument shapes and version-specific details.

// Playwright examples
const existing = await context.cookies('https://example.com');
await context.addCookies([
  { name: 'session', value: 'test-value', url: 'https://example.com' }
]);
await context.clearCookies();

The cookie above is a minimal example for a test environment, not a production credential. Real applications may require appropriate domain, path, expiry, and security attributes. Playwright’s migration guide maps Puppeteer’s page.setCookie(...cookies) to browserContext.addCookies(cookies), page.cookies([...urls]) to browserContext.cookies([...urls]), and cookie deletion to browserContext.clearCookies(). For new Playwright code, prefer context-level cookie APIs. See Playwright’s Puppeteer migration guide and the Puppeteer cookies guide.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
Acer Wireless Mouse for Laptop, 2.4GHz Computer Mouse 3 Adjustable 1600 DPI
  • 【Plug and Play for Home/Office/School】The wireless computer mouse features 2.4GHz connectivity, delivering a stable, interference-free connection up to 32ft. Designed for 𝐦𝐞𝐝𝐢𝐮𝐦 𝐭𝐨 𝐥𝐚𝐫𝐠𝐞 𝐬𝐢𝐳𝐞𝐝 𝐡𝐚𝐧𝐝𝐬, it ensures comfortable use all day. Simply plug in the USB-A receiver for instant pairing—no drivers needed. 📌📌 If the mouse isn’t suitable, place the USB receiver in the battery compartment and return both.
  • 【3 Levels Adjustable DPI】This travel USB mouse offers 3 adjustable DPI settings (800, 1200, 1600), allowing you to customize sensitivity for precise design work. Effortlessly switch to match your task and elevate your productivity. 📌 Please remove the film at the bottom of the mouse before use.
  • 【Effortless Browsing】Equipped with forward and backward buttons, this computer mice streamlines your workflow, making it easy to navigate through web pages and files with a simple click. 📌Side button does not work on Mac.
  • 【Visible Indicator Light】 The pc mouse features a visual indicator for DPI levels and low battery alerts. The red light flashes once for 800 DPI, twice for 1200 DPI, and three times for 1600 DPI. When the battery level is below 10%, the light flashes red until the mouse is completely out of power.
  • 【Click to Wake】With smart sleep mode, it saves power by standby after 10 inactive minutes, just 2-3 clicks to wake. This efficient design delivers 3x longer battery life than motion-wake mice. Engineered for durability, its buttons and scroll wheel are tested for 10 million clicks, ensuring long-term reliability and consistent performance.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose the right session approach

Need Recommended approach Important detail
Separate users or isolated work One context per identity or isolated task Pages in the same context share session identity; separate contexts isolate it.
Fresh Playwright test sessions Use Playwright Test’s default per-test context A fresh context reduces state carry-over between tests.
Reuse a Playwright login Save and load storageState Protect the file as a secret; determine whether cookies, local storage, or IndexedDB are required.
Restore Playwright sessionStorage Capture selected values and use a host-scoped addInitScript Normal storage-state saving does not include sessionStorage.
Set or clear cookies Use context-level cookie methods Cookies may not be the application’s only authentication state.
Persist Puppeteer storage for later runs Use documented context and cookie operations for the installed version The reviewed Puppeteer references establish context isolation and cookie operations, but do not establish an equivalent general storage-state workflow.

Troubleshooting session problems

A page appears logged out after loading saved state

  • Check that the state was saved after the login completed and was saved from the context that performed that login.
  • Determine which storage the application actually uses. Cookies alone may not be enough; local storage, IndexedDB, or other credentials may also be involved.
  • Check whether the session expired or the application invalidated it. Re-authenticate and capture fresh state rather than treating an expired file as permanent.

sessionStorage is empty in the new context

  • This is expected with the ordinary Playwright storage-state workflow. Capture the values separately and install a scoped initialization script before navigating to the app.
  • Confirm the hostname or origin check matches the page being opened and that the script is installed on the context before the page loads.

Cookies do not apply to the page

  • Check that the cookie’s URL or domain/path scope matches the destination and that security attributes are suitable for the test URL.
  • Use the context API for the context that owns the page. Adding a cookie to one context does not establish it in another.
  • Check the framework’s current reference for required fields and supported attributes.

One test changes another test’s login

  • Use separate contexts for identities that must be isolated. In Playwright Test, avoid accidentally sharing a manually created context across tests that are intended to be independent.
  • Remember that pages and popups in one context share its identity and storage.

Closing a browser context fails

  • Do not attempt to close the browser’s default context. Create a managed context with browser.newContext() in Playwright or browser.createBrowserContext() in Puppeteer, then close that context.
  • Close the managed context to close all its pages; close the browser separately when the process is finished.

Performance, reliability, and cost considerations

Contexts are useful for organizing isolation and cleanup: a context can own the pages for one task, and closing it releases that session’s pages together. Reusing a saved Playwright state can avoid repeating an interactive login flow, but it adds credential-file security and expiration concerns. For reliable tests, keep identities and test data isolated, create state deliberately, and regenerate saved state when the application’s authentication expires. No universal timing or cost figure follows from these APIs; actual runtime depends on the browser, application, network, and work performed.

Or skip the browser setup

If your goal is a screenshot rather than controlling an interactive session, ScreenshotNeo offers a one-request screenshot API. It can accept cookie and consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. An MCP server exposes take_screenshot, get_page_info, and capture_pdf for AI agents.

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

See the ScreenshotNeo API documentation for parameters and response details. Its free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month, with no card required.

Frequently Asked Questions

Can pages in one browser context share a login?

Yes. Pages and popups in the same context share that context’s session identity and storage.

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.

Does Playwright storageState save sessionStorage?

No. Capture and restore the needed sessionStorage values separately, using an initialization script scoped to the intended site.

Should I commit Playwright authentication state to a private repository?

No. Treat saved state as a credential that may enable account impersonation and keep it out of source control.

Quick Recap

SaleBestseller No. 1
Logitech M185 Compact Ambidextrous 2.4 GHz Wireless Mouse - Swift Grey
Logitech M185 Compact Ambidextrous 2.4 GHz Wireless Mouse - Swift Grey
Product carbon footprint: 3.97 kg CO2e; Contoured shape: Gives you more comfort and control
$12.34
SaleBestseller No. 3
SaleBestseller No. 4
Amazon Basics 3-Button USB Wired Mouse with Responsive Tracking, Plug & Play, Compatible with Windows and Mac, Black
Amazon Basics 3-Button USB Wired Mouse with Responsive Tracking, Plug & Play, Compatible with Windows and Mac, Black
Computer mouse for easily navigating a computer interface; click, scroll, and more; 3 buttons offer effortless fingertip control
$6.79

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.