iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
Use BrowserContext when you need separate browser-managed storage for automation tasks, cookie methods when you need to inspect or change particular cookies, and userDataDir when you need to choose the browser’s user-data directory at launch. These are different controls: cookie operations do not create an isolated context, and a context does not amount to a promise that state will persist across browser launches.
Choose the right Puppeteer storage mechanism
There are three related but distinct choices:
| Need | Use | What it controls |
|---|---|---|
| Read, set, or delete particular cookies | BrowserContext.cookies(), setCookie(), and deleteCookie() |
Cookie operations in the context you select. |
| Keep browser-managed storage separate between tasks | A separate BrowserContext |
Storage isolation, including cookies and local storage, between contexts. |
| Choose a browser user-data directory | launch({userDataDir: ...}) |
A launch-time path setting for the browser’s user data directory. |
Use the context-level methods when you want to be explicit about which task’s state you are touching. The corresponding Browser cookie methods are shortcuts for the default context. The Puppeteer 25.12.0 documentation describes these APIs; individual cookie-method reference pages have also appeared as version 25.11.0, so check the official API reference for the version installed in your project.
Read, set, and delete cookies
Cookies belong to a browser context. A common mistake is to operate through the browser shortcut while a page being automated belongs to a different context. Retrieve the page’s context, then use that context for the operation.
Runnable example
This example launches Chrome, opens a page, reads that page context’s cookies, sets a cookie, reads them again, deletes the cookie, and closes the browser. Replace the example URL and cookie values with ones appropriate for a site you are authorized to automate.
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({ headless: true });
try {
const page = await browser.newPage();
await page.goto('https://example.com');
const context = page.browserContext();
const before = await context.cookies();
console.log('Cookies before:', before);
await context.setCookie({
name: 'automation-example',
value: 'sample-value',
domain: 'example.com',
path: '/',
secure: true,
httpOnly: true,
sameSite: 'Lax'
});
console.log('Cookies after setting:', await context.cookies());
await context.deleteCookie({
name: 'automation-example',
domain: 'example.com',
path: '/'
});
console.log('Cookies after deleting:', await context.cookies());
} finally {
await browser.close();
}
})();
Cookie data includes a name and domain and supports optional attributes such as expires, httpOnly, secure, path, and sameSite. If expires is omitted, Puppeteer’s CookieData reference describes the cookie as a session cookie. Its acceptance and meaning are still determined by the target site and cookie attributes: adding a cookie does not, by itself, authenticate you or guarantee a valid session.
Use the browser shortcuts only for the default context
browser.cookies(), browser.setCookie(), and browser.deleteCookie() act on the default context. They are convenient when your pages are in that context. If you have created a separate context, use its methods instead; otherwise you may inspect or mutate the wrong storage.
Separate automation sessions with BrowserContext
A BrowserContext represents an individual user context. Puppeteer documents cookies and local storage as isolated between contexts. This makes contexts useful for keeping tasks apart—for example, running two test identities without intentionally sharing their browser-managed storage.
Rank #2
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({ headless: true });
try {
const contextA = await browser.createBrowserContext();
const contextB = await browser.createBrowserContext();
const pageA = await contextA.newPage();
const pageB = await contextB.newPage();
await Promise.all([
pageA.goto('https://example.com'),
pageB.goto('https://example.com')
]);
console.log('A cookies:', await contextA.cookies());
console.log('B cookies:', await contextB.cookies());
await contextA.close();
await contextB.close();
} finally {
await browser.close();
}
})();
In Chrome, Puppeteer documents non-default contexts as incognito. The default context can also be incognito when Chrome is launched with --incognito. A context can create pages and be closed after its task is finished. Context isolation is not the same as selecting a user-data directory, and the API description does not establish that a context’s state will be a persistent profile available to a later browser launch.
Set a user-data directory at launch
LaunchOptions.userDataDir accepts a path to a browser user-data directory. This is a browser launch configuration, rather than a cookie operation or per-context isolation feature.
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({
headless: true,
userDataDir: './puppeteer-user-data'
});
try {
const page = await browser.newPage();
await page.goto('https://example.com');
console.log(await page.title());
} finally {
await browser.close();
}
})();
The path above is an example; choose a directory appropriate to your runtime and deployment. The documented option establishes that Puppeteer can be given a user-data-directory path. It does not, on its own, settle exactly what state will survive a restart, how profile migration should work, whether a directory can safely be used concurrently, or how it should be backed up. Treat those as operational questions for your specific browser, environment, and workload rather than inferring guarantees from the option’s existence.
Close the browser or disconnect Puppeteer
These methods control the browser process, not cookie expiry or the persistence policy for a profile.
await browser.close()closes the browser that Puppeteer launched.await browser.disconnect()detaches Puppeteer while leaving the browser process and its pages open.
Use close() when the automation run should finish by shutting down its browser. Use disconnect() when Puppeteer should stop controlling a browser that is meant to keep running. Disconnecting is not a way to close a browser cleanly, and neither method changes a cookie’s session-versus-expiration attributes.
Common errors and how to diagnose them
- The cookie list is empty or unexpected. Confirm that you are querying the context that owns the page. Browser-level cookie methods refer to the default context; a separately created context has its own storage.
- A cookie is not accepted or does not appear to work. Check that its domain and other supplied attributes match the target site’s requirements. A successful API call does not prove that the site will treat the cookie as an authenticated session.
- A cookie disappears when the session ends. If no
expiresvalue was supplied, the API reference classifies it as a session cookie. Whether a cookie with an expiry is retained in a particular deployment is not a guarantee established by the cookie method description. - Two tasks see different storage. Verify that both pages were created in the same context if they are meant to share context storage, or in different contexts if they are meant to be isolated. Do not use the default-context shortcut to inspect another context.
- A browser remains open after automation stops. Check whether the code called
disconnect()rather thanclose(). Disconnect deliberately leaves the browser and pages running. - A user-data directory behaves differently after restart than expected. The
userDataDiroption documents a path, not every lifecycle or durability detail. Confirm the behavior with the installed Puppeteer and Chrome versions and the deployment’s profile-handling requirements.
Operational notes: reliability, performance, and cost
These APIs provide different scopes of control, so choose the narrowest mechanism that satisfies the task: explicit cookie calls for targeted cookie work, a context for storage separation, and a launch directory when the browser needs a designated user-data path. Keep cleanup in a finally block so an exception does not skip the intended browser shutdown. If you need to leave a browser process alive, make that an explicit lifecycle choice and use disconnect() knowingly.
Rank #4
The cited Puppeteer documentation does not provide a performance benchmark, a concurrency guarantee for sharing a data directory, or a complete backup and migration procedure. Do not infer those properties from the method names. Validate directory ownership, process coordination, storage retention, and recovery behavior in the exact runtime you deploy. For API signatures and current behavior, consult the official documentation for your installed Puppeteer release.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Or skip the browser setup
If the goal is a screenshot rather than managing an authenticated browser session or profile directory, ScreenshotNeo can capture a URL with one GET request. Its cookie-banner handling accepts consent banners as a visitor and removes 60+ known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in headers. It also offers an MCP server for AI agents, with take_screenshot, get_page_info, and capture_pdf.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutecurl -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 request options. ScreenshotNeo is a screenshot service, not a replacement for Puppeteer cookie/session operations or a browser user-data directory. Its Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 shots.
Sign up for ScreenshotNeo’s free plan for 1,000 screenshots a month with no card.
Best Value
Frequently Asked Questions
Which Puppeteer API should I use to read cookies from a page?
Get the page’s BrowserContext and call its cookie method so the operation targets that page’s context.
Does BrowserContext isolation guarantee a saved session next time I launch Puppeteer?
No such cross-launch persistence guarantee is established by the context API description. Use the documented behavior of your installed version and environment to assess persistence.
Free tools Windows power users keep installed
One-click scans. No signup required.
Does disconnecting Puppeteer close Chrome?
No. Disconnect detaches Puppeteer and leaves the browser process and its pages open; close shuts down the launched browser.
Quick Recap
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.

