How to Set Cookies in Puppeteer
Set cookies in Puppeteer’s browser context before navigation. Learn the current API, cookie scope, common fixes, and a simpler screenshot option.
Use BrowserContext.setCookie() on the context that owns the page, then navigate to the site. For the default browser context, browser.setCookie() is a shortcut. The current Puppeteer documentation marks page.setCookie() obsolete.
const context = page.browserContext();
await context.setCookie({
name: 'session',
value: 'example-value',
domain: 'example.com',
path: '/',
httpOnly: true,
secure: true,
sameSite: 'Lax',
});
await page.goto('https://example.com');
This guide covers cookie scope, the fields you are likely to need, context isolation, migration from page.setCookie(), and debugging. The example follows Puppeteer’s documented API; it has not been run against a live browser or site.
1. Set a cookie before navigating
Set the cookie on the page’s browser context before calling page.goto(). The cookie must be scoped to the destination using a matching domain or URL and, where relevant, path and security settings.
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
const context = page.browserContext();
await context.setCookie({
name: 'session',
value: 'example-value',
domain: 'example.com',
path: '/',
httpOnly: true,
secure: true,
sameSite: 'Lax',
});
await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
console.log('Loaded:', page.url());
} finally {
await browser.close();
}
})();
For an ES module project, the same sequence works with import puppeteer from 'puppeteer' and top-level await, if your Node.js project supports it.
The ordering matters: set the cookie before navigation so it is available when the browser makes the site request. Use the context associated with the page you will navigate. Puppeteer documents BrowserContext.setCookie() as accepting one or more cookie data objects and returning a promise. See the official BrowserContext.setCookie API reference and CookieData reference.
2. Choose the right browser context
Cookies belong to a browser context. A context created with browser.createBrowserContext() has isolated storage, including cookies and local storage. Setting a cookie in one context does not configure a page using another context.
Use the page’s context
When you already have a page, get its context and set the cookie there:
const context = page.browserContext();
await context.setCookie({
name: 'theme',
value: 'dark',
url: 'https://example.com',
});
Use the default context
If the page is in the default context, the browser-level shortcut is available:
await browser.setCookie({
name: 'theme',
value: 'dark',
url: 'https://example.com',
});
const page = await browser.newPage();
await page.goto('https://example.com');
browser.setCookie() sets cookies in the default browser context. Prefer the explicit context method when your code manages multiple contexts, so it is clear which session receives the cookie. The Browser.setCookie reference documents the shortcut.
3. Set multiple cookies
Pass multiple cookie data objects to the context in one call. Give each cookie a name, value, and scope that matches the target site.
await context.setCookie(
{
name: 'session',
value: 'example-session',
url: 'https://example.com',
httpOnly: true,
secure: true,
sameSite: 'Lax',
},
{
name: 'locale',
value: 'en',
url: 'https://example.com',
path: '/',
},
);
await page.goto('https://example.com');
Use one object per cookie. Avoid placing real session secrets in source code or logs; load them from your application’s secret store or environment configuration.
4. Cookie fields and scope
The current CookieData interface requires name and value. It documents scope and optional fields for expiry, security, SameSite, partitioning, priority, source scheme, and URL. Browser support and exact field behavior can depend on the Puppeteer and browser versions in your project.
| Field | Purpose and guidance |
|---|---|
name |
Required cookie name, such as session. |
value |
Required cookie value. |
domain |
Cookie domain scope. It must match the destination host and intended subdomain scope. |
path |
Path scope. Use / when the cookie should apply across the site. |
url |
Can be used to derive default domain, path, and source-scheme values. Use a URL matching the target site. |
expires |
Expiration date represented as a number. If omitted, the cookie is a session cookie. |
httpOnly |
Set when client-side scripts should not access the cookie. Choose this according to the application’s requirements. |
secure |
Set to true for cookies intended for secure transport over HTTPS. |
sameSite |
Controls cross-site sending behavior. Use a value that matches the application’s authentication and navigation requirements. |
partitionKey |
Partitioned cookie data; use only when your application and browser support the required behavior. |
priority |
Cookie priority where supported by the browser and Puppeteer version. |
sourceScheme |
Source scheme metadata where supported. Check the installed version’s API reference before relying on it. |
For most automation, specify either a matching url or a deliberate domain and path. Do not assume an incorrectly scoped cookie will be sent just because it exists in browser storage. The official CookieData reference lists the current interface fields.
Example with an expiry
The expires value is a numeric expiration date. If a persistent cookie is required, supply the value in the form expected by the documented browser API and verify it against your installed Puppeteer version.
await context.setCookie({
name: 'preference',
value: 'compact',
url: 'https://example.com',
expires: 1893456000,
});
5. Migrate from page.setCookie()
If older code calls page.setCookie(), move the call to the page’s browser context:
// Older page-level form; obsolete in current Puppeteer documentation:
// await page.setCookie(cookie);
// Current context-level form:
await page.browserContext().setCookie(cookie);
The current Page API reference directs users to Browser.setCookie() or BrowserContext.setCookie(). Use the browser shortcut only when the default context is the intended one; otherwise use the target page’s context. See the official Page.setCookie reference.
6. Check which cookies are stored
To inspect cookies stored in the default browser context, use browser.cookies():
const cookies = await browser.cookies();
console.log(cookies.map(({ name, domain, path, secure, httpOnly }) => ({
name,
domain,
path,
secure,
httpOnly,
})));
This method reports cookies for the default context. If your page belongs to a separately created context, inspect storage through APIs and tools available for that context and your installed Puppeteer version rather than assuming the default-context result applies. See the official Browser.cookies reference.
7. Common errors and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| The site behaves as if the cookie is missing | The cookie was set after navigation, or its domain, URL, or path does not match the request. | Set it before page.goto(); check the target hostname and path; use a matching url or explicit scope. |
| Cookie appears in one page but not another | The pages use different browser contexts. | Set the cookie on the context that owns the destination page. Contexts isolate cookie storage. |
page.setCookie is flagged as obsolete |
The current Page API marks that method obsolete. | Replace it with page.browserContext().setCookie() or, for the default context, browser.setCookie(). |
| Cookie is not sent over the expected connection | Secure transport or cookie scope may not match the request. | Check that the page uses HTTPS when secure: true, and verify domain and path scope. |
| Cookie expires sooner than expected | The cookie was set without a persistent expiration or with an incorrect numeric expiry. | Omit expires only for a session cookie; otherwise supply and verify the intended expiration value. |
| A browser-specific cookie field is rejected or ignored | The installed Puppeteer or browser version may not support that field. | Check the API reference for the project’s installed version and test the field in the target browser. |
8. Reliability, performance, and security notes
- Set cookies before the first relevant request. This avoids making an initial unauthenticated navigation when the cookie is needed for the page load.
- Keep context ownership explicit. Reuse the intended context for the page and its cookies; creating another context creates a separate storage area.
- Keep secrets out of source and output. Session values can grant access. Read them from protected configuration and avoid logging their values.
- Use application-appropriate flags. Set
httpOnly,secure, andsameSitebased on how the real application issues and consumes the cookie. - Check version-specific behavior. The indexed official references consulted for this article displayed Puppeteer API versions 25.11.0 and 25.12.0. Confirm the API for the version installed in your project, especially for browser-specific fields.
Cookie setup itself is a small browser operation; the larger runtime cost usually comes from launching the browser and loading the page. Reuse a browser process when appropriate, while keeping separate contexts where session isolation is required. No benchmark is implied here.
9. Or skip the browser setup
If you need a website screenshot rather than browser automation, ScreenshotNeo is a website screenshot API and MCP server from Yorker Media. One GET request returns a PNG, JPEG, WebP, or PDF. See the ScreenshotNeo documentation.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo removes cookie and consent banners, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed. Its MCP server gives AI agents tools for screenshots, page information, and PDF capture. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Every feature is on every plan. This is a screenshot service, so use Puppeteer when you need to control browser session cookies or automate other browser actions.
Sign up for ScreenshotNeo’s free plan: 1,000 screenshots a month, no card required.
10. FAQ
Can I set a cookie after opening the page?
You can set one on the page’s context, but if the cookie is needed for the initial request, set it before navigation. Otherwise, navigate again if your workflow needs the next request to include it.
Does a new Puppeteer context share cookies with the default context?
No. Browser contexts isolate cookies and other storage. Set the cookie in the context that owns the target page.
Should I use url or domain?
Either can be used to establish scope. A matching url can determine default domain, path, and source-scheme values; use explicit domain and path when you need to control that scope directly.
Where can I verify the exact API for my version?
Use the official Puppeteer API reference for the version installed in your project, particularly for optional fields that depend on browser support.


