Browser Context APIs: Isolated Sessions Guide
In this article
Browser Context APIs let you create completely isolated browsing sessions within a single browser instance, each with its own cookies, storage, cache, and permissions. This is invaluable for testing multi-account workflows, debugging authentication flows, or running parallel automation tasks without cross-contamination. You can achieve this using Playwright's browser.newContext(), Puppeteer's browser.createBrowserContext(), or Selenium's ChromeOptions with separate user-data directories. This guide walks you through the practical steps for each approach.
What You'll Need
- Node.js (v16 or later) installed for Playwright/Puppeteer examples
- Python 3.7+ with Selenium installed if using the Selenium approach
- A code editor and terminal
- Basic familiarity with JavaScript or Python and async/await patterns
Step-by-Step
Using Playwright (Recommended)
- Install Playwright – Run
npm init -ythennpm install playwright. Follow withnpx playwright installto download browsers. - Launch a browser instance – In your script, import
chromiumfromplaywrightand callchromium.launch(). This creates the main browser process. - Create a new context – Use
const context = await browser.newContext(). Each context is fully isolated: it gets fresh cookies, localStorage, and cache. You can pass options likeviewport,locale, orpermissionshere. - Open a page in that context –
const page = await context.newPage(). This page belongs exclusively to that context and shares nothing with other contexts. - Create multiple contexts for parallel sessions – Repeat step 3 to create as many isolated sessions as needed. Each context can have multiple pages, but they all share the same storage.
- Close contexts individually – When done, call
await context.close()to clear all data and free resources. Closing a context does not affect other contexts or the browser itself. - Close the browser – Finally,
await browser.close()to terminate all remaining contexts and the browser process.
Using Puppeteer
- Install Puppeteer – Run
npm install puppeteer. It downloads Chromium automatically. - Launch the browser –
const browser = await puppeteer.launch(). - Create a browser context –
const context = await browser.createBrowserContext(). This returns aBrowserContextobject. - Open a page in that context –
const page = await context.newPage(). The page is isolated from any other context. - Create multiple contexts – Call
createBrowserContext()again for each separate session. You can also pass options likepermissionsorlocale. - Close contexts – Use
await context.close()to destroy the context and its data. Note: In Puppeteer, closing a context also closes any pages inside it. - Close the browser –
await browser.close()after all contexts are done.
Using Selenium (Python)
- Install Selenium –
pip install selenium. Also download the appropriate ChromeDriver. - Set up separate user-data directories – For each isolated session, create a unique folder, e.g.,
session_1,session_2. These store cookies and cache separately. - Configure Chrome options –
options = webdriver.ChromeOptions()thenoptions.add_argument(f"user-data-dir={path_to_folder}"). - Launch a driver per session –
driver = webdriver.Chrome(options=options). Each driver with a different user-data-dir is fully isolated. - Run your tests – Use each driver independently. They share nothing.
- Quit drivers – Call
driver.quit()for each session to close and clean up.
Common Mistakes
- Reusing a page across contexts – Pages are bound to their context. You cannot move a page to another context; create a new page instead.
- Forgetting to close contexts – Leaving contexts open consumes memory and can cause resource leaks, especially in long-running scripts.
- Using the default context for everything – The default context in Playwright/Puppeteer is shared; if you need isolation, always create a new context rather than using the default one.
- Sharing user-data-dir in Selenium – If two drivers use the same folder, they will conflict and may crash. Always use unique directories.
- Assuming storage is isolated across pages in the same context – Pages within the same context share cookies and localStorage. Only separate contexts provide full isolation.
Tips
- Use context options for realism – Set
viewport,locale,timezoneId, andpermissionsto simulate different users or regions. - Persist contexts for reuse – In Playwright, you can save a context's storage state with
context.storageState()and reload it later viabrowser.newContext({ storageState }). - Run contexts in parallel – Use
Promise.allin Playwright/Puppeteer to execute multiple isolated sessions concurrently for faster testing. - Monitor resource usage – Each context adds overhead. Limit the number of concurrent contexts to what your system can handle.
- Clean up in finally blocks – Wrap your code in try/finally to ensure contexts are closed even if an error occurs.
Troubleshooting
- Contexts are not isolating cookies – Verify you are creating a new context and not reusing the default one. In Playwright, check that you call
browser.newContext()and notpage.context(). - Browser crashes when creating many contexts – Reduce the number of concurrent contexts or increase system memory. Also ensure you close contexts promptly.
- Selenium sessions interfere – Make sure each driver uses a unique
user-data-dir. Also add--no-sandboxif running as root in Linux. - Pages load slowly in isolated contexts – This may be due to cold caches. Pre-warm the context by visiting a blank page or using
context.setDefaultNavigationTimeout()to adjust timeouts. - Storage state not saving – In Playwright, ensure you call
storageState()after the page has fully loaded and before closing the context. Save the JSON file to disk.
Frequently Asked Questions
Can I share cookies between two contexts?
No, contexts are designed to be isolated. If you need shared cookies, use the same context for both pages, or manually copy cookies via context.cookies() and context.addCookies().
How many contexts can I create?
There is no hard limit, but each context consumes memory and file descriptors. In practice, you can create dozens on a typical machine; beyond that, performance degrades.
Does closing a context delete its data permanently?
Yes, closing a context discards all cookies, storage, and cache associated with it. If you need to preserve data, use storageState() before closing.
Can I use contexts with mobile emulation?
Yes, in Playwright and Puppeteer you can pass viewport and userAgent options when creating a context to simulate mobile devices.
Are contexts supported in all browsers?
Playwright and Puppeteer support contexts in Chromium, Firefox, and WebKit. Selenium's method with user-data-dir works only with Chromium-based browsers.
What is the difference between a context and a page?
A context is a container with its own storage and permissions. A page is a single tab within that container. Multiple pages can exist in one context and share its storage.