Browser Automation Contexts: Organize Like a Pro
In this article
Organizing browser automation contexts keeps your scripts fast, stable, and easy to debug. Instead of one messy browser session, you create isolated environments (contexts) for different tasks—like separate logins, test users, or scraping jobs. This prevents data leaks, speeds up parallel runs, and makes failures easier to isolate. You'll need a browser automation library such as Playwright or Puppeteer, and a basic understanding of async/await in JavaScript (or your language's equivalent).
What You'll Need
- Node.js (or Python with Playwright/Pyppeteer) installed
- A browser automation library (Playwright recommended, Puppeteer works too)
- A code editor and a test site with login functionality (for practice)
Step-by-Step
- Plan your context breakdown. Decide what each context will do. For example: one context for admin tasks, one for regular user actions, one for anonymous browsing. Keep contexts single-purpose—this makes cleanup and debugging simpler.
- Create a fresh browser instance. In Playwright:
const browser = await chromium.launch(). This launches the browser but no pages yet. You'll create contexts from this browser. - Create a new context for each distinct task. Use
const context = await browser.newContext(). Each context has its own storage (cookies, localStorage) and user agent. For parallel tasks, create multiple contexts from the same browser. - Open pages inside the context. Use
const page = await context.newPage(). Always create pages from the context, not the browser, to keep them isolated. Never mix pages from different contexts in the same logic flow. - Configure context-specific settings. Pass options to
newContext():viewport,userAgent,locale,geolocation, orpermissions. This lets you simulate different devices or regions without extra code. - Authenticate within each context separately. For a login flow, perform it once per context and reuse that context for subsequent actions. Don't share cookies across contexts—that defeats the isolation.
- Use context-level storage state. Save and load authenticated states using
context.storageState()andbrowser.newContext({ storageState: 'state.json' }). This lets you skip re-login for repeat runs. - Run contexts in parallel. Use
Promise.all()or a worker pool to run multiple contexts simultaneously. Each context runs independently, so parallel execution is safe as long as they don't share external resources. - Close contexts when done. Call
await context.close()to free memory and clear temporary data. Don't leave contexts open—they accumulate and slow down the browser. - Finally, close the browser. After all contexts are closed,
await browser.close(). This ensures all processes exit cleanly.
Common Mistakes
- Using one context for everything. This mixes cookies and cache, leading to unexpected state leakage between tasks.
- Creating contexts but never closing them. Memory leaks and browser slowdowns are common when contexts pile up.
- Sharing page objects across contexts. A page belongs to one context; using it in another throws errors or causes race conditions.
- Assuming contexts share nothing by default. They do share the same browser process and some system-level resources, so keep heavy parallel loads reasonable.
- Hard-coding storage state paths. If you change the login flow, the saved state becomes stale. Always regenerate it.
Tips
- Name your contexts meaningfully (e.g.,
adminContext,userContext) to make code readable. - Use a helper function to create and return a context with default settings, so you don't repeat configuration.
- For long-running tasks, periodically close and recreate contexts to avoid memory bloat.
- When testing, use
context.route()to intercept network requests and simulate slow or failing responses per context. - Store storage state files in a temp folder and clean them up after tests.
Troubleshooting
Contexts seem to share cookies. Check that you're creating pages from the context, not from the browser. Also verify you didn't accidentally pass the same storageState to multiple contexts.
Parallel contexts slow down or crash. Reduce the number of concurrent contexts. Each context uses memory; try closing contexts after each task and reusing a browser instance with fewer contexts at a time.
Login state doesn't persist. Make sure you wait for navigation to complete after login before saving storageState(). Also, some sites use sessionStorage—that isn't saved by storageState(); you may need to handle that separately.
Context creation fails with permission errors. Check your browser launch options. In some environments, you need to pass --no-sandbox or set headless: false if running as root.
Pages open in the wrong context. Verify you're calling context.newPage() and not browser.newPage() (which doesn't exist in Playwright, but in Puppeteer it creates a page in the default context). Always use the context object.
Frequently Asked Questions
What is the difference between a browser and a context in Playwright?
A browser is the actual Chromium/Firefox process. A context is an isolated incognito-like session within that browser. Multiple contexts can exist in one browser, each with its own cookies, localStorage, and cache.
Can I reuse a context after closing it?
No. Once you call context.close(), the context is destroyed. You must create a new one. If you need to reuse state, save it with storageState() and load it into a new context.
How many contexts can I create in one browser?
There's no hard limit, but each context consumes memory. In practice, 10–20 concurrent contexts are fine on a typical machine. Beyond that, you may hit resource limits.
Do contexts share proxy settings?
Yes, if you set a proxy at the browser level, all contexts inherit it. To use different proxies per context, pass a proxy option to newContext().
Is it better to use one browser with many contexts or many browsers?
One browser with many contexts is lighter and faster. Multiple browsers are only needed if you want completely separate processes (e.g., for running different browser versions).
Can I change the user agent per context?
Yes, pass userAgent in the context options. This is useful for simulating different devices or bypassing mobile detection (though not for bypassing blocks).