Puppeteer CookieParam: Set Cookies with Options
Set cookies in Puppeteer with the right scope, expiry, security attributes, and browser context. Includes runnable JavaScript, troubleshooting, and a screenshot API option.
Puppeteer cookies are objects with required name and value fields plus optional scope, lifetime, and security fields. In current Puppeteer, set them with Browser.setCookie() or BrowserContext.setCookie(); the page-level Page.setCookie() API is obsolete. Choose only the attributes that match the cookie and the site you are automating.
The examples below use current browser or context methods and JavaScript. See Puppeteer’s CookieParam reference, BrowserContext.setCookie reference, and cookies guide.
1. Set a cookie with Puppeteer
Install Puppeteer in a Node.js project with npm install puppeteer. This runnable script launches Chromium, opens a page on the matching host, sets a cookie in that browser context, reads the cookies visible to the page, and closes the browser.
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({ headless: true });
try {
const context = browser.defaultBrowserContext();
const page = await context.newPage();
await page.goto('http://localhost:3000', { waitUntil: 'domcontentloaded' });
await context.setCookie({
name: 'theme',
value: 'dark',
url: 'http://localhost:3000',
path: '/',
sameSite: 'Lax',
});
console.log(await page.cookies());
} finally {
await browser.close();
}
})();
The host must match the cookie’s scope. Replace the localhost URL with the origin your test uses. For a production authentication cookie, use the real cookie attributes and a secure test environment; do not copy localhost-oriented or insecure examples as defaults.
Choose browser or context scope
context.setCookie(...cookies)sets cookies in that browser context. Use a deliberately selected context when you need isolated storage between tests, users, or sessions.browser.setCookie(...cookies)is a shortcut for the default browser context.page.setCookie()is obsolete in current Puppeteer documentation. Prefer browser- or context-level methods.
Browser contexts isolate storage, including cookies and local storage. A separate context is useful when one test’s login state must not leak into another test.
2. CookieParam options
name and value are required. The other fields are optional; choose them based on the site cookie you are representing, not by filling every field automatically.
| Option | Meaning and when to use it |
|---|---|
name |
Required string identifying the cookie. |
value |
Required string containing its value. |
url |
Request URI associated with setting the cookie. It can affect default domain, path, and source scheme. Prefer it when you know the target URL and want Puppeteer to derive applicable defaults. |
domain |
Cookie domain. Set this to match the intended host or domain scope. A cookie scoped to one host should not be assumed to apply to its sibling hosts. |
path |
Path scope. Use the site’s intended path; / is commonly used when the cookie should cover the whole host. |
expires |
Expiration timestamp as a number. Omit it for a session cookie. Match the target cookie’s expiry semantics. |
httpOnly |
Boolean controlling whether page JavaScript can read the cookie. Set it to match the cookie under test. |
secure |
Boolean indicating a secure cookie. Match the site’s requirement and the URL scheme used by the test. |
sameSite |
SameSite type. Use the value that matches the intended cross-site behavior of the cookie. |
partitionKey |
A CookiePartitionKey or string for partitioned cookies. In Chrome it matches the top-level site for the partition; in Firefox it matches the source origin in the partition key. |
priority |
Cookie priority; supported only in Chrome. |
sourceScheme |
Cookie source scheme; supported only in Chrome. |
Scope, lifetime, and security choices
- Scope: choose between a URL-derived scope and explicit
domainandpath. Ensure the page you visit falls within that scope. - Lifetime: omit
expiresfor a session cookie; provide it when the cookie should persist to a specific expiration. - Visibility and transport: set
httpOnly,secure, andsameSiteaccording to the behavior being tested. These attributes are not interchangeable. - Browser support: partitioning and Chrome-only fields need deliberate browser-specific handling. Do not assume a Chrome-only option behaves the same in other browsers.
Puppeteer’s guide shows a localhost example with two cookies and fields such as expires: -1, httpOnly: false, secure: false, and sourceScheme: 'NonSecure'. Treat that as a documentation example, not a production recipe for authentication cookies.
3. Set multiple cookies or isolate test sessions
The set-cookie methods accept cookie data objects. You can pass multiple objects to one call, and use a fresh context when each test needs its own storage.
const context = await browser.createBrowserContext();
try {
const page = await context.newPage();
await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
await context.setCookie(
{
name: 'language',
value: 'en',
url: 'https://example.com',
path: '/',
},
{
name: 'session_hint',
value: 'test-session',
url: 'https://example.com',
httpOnly: true,
secure: true,
sameSite: 'Lax',
},
);
await page.reload({ waitUntil: 'domcontentloaded' });
console.log(await page.cookies());
} finally {
await context.close();
}
Set cookies before the navigation whose behavior depends on them when possible. If the domain is not available until after navigation, first visit the relevant origin, set the cookie, then reload or navigate to the page under test. The right order depends on how the application reads the cookie.
4. Verify the cookie and common failure cases
After setting a cookie, inspect the cookies for the target page with page.cookies() and verify the page’s observed behavior. A successful API call alone does not establish that the application accepts the cookie or that it authenticates a user.
| Symptom | Likely cause | Fix |
|---|---|---|
Cookie is missing from page.cookies() |
The cookie’s domain, path, URL, or context does not match the page being inspected. | Set it in the same context as the page. Use a matching url or check explicit domain and path, then inspect cookies for the exact page URL. |
| Cookie is present but the server ignores it | Its value or security attributes do not match the site’s expected cookie, or the application has another authentication requirement. | Compare the test data with the site’s actual cookie semantics. Do not assume that injecting a cookie bypasses authentication. |
| Cookie does not persist after closing the browser | No persistent expiry was provided, so it is a session cookie. | Set an appropriate expires value if the test requires persistence; otherwise keep session behavior. |
| Cookie is not sent on the tested request | The request’s host, path, scheme, or cross-site context does not fit the cookie’s scope or attributes. | Check URL/domain/path, HTTPS for secure cookies, and the intended SameSite behavior. |
| A field is rejected or has no effect in another browser | The option may be browser-specific; priority and sourceScheme are Chrome-only. |
Check the target browser’s support and omit browser-specific fields when they are not applicable. |
| Changes appear in another test unexpectedly | Tests reused a context whose cookie storage was shared. | Create a separate BrowserContext per isolated test or session and close it when finished. |
5. Performance, reliability, and cost
Cookie setup is usually a small step compared with browser launch, navigation, and page readiness, but the exact time depends on the site and environment. Reuse a browser process when appropriate and isolate state with contexts; close contexts and browsers in finally blocks so failures do not leave browser resources behind. Avoid relying on a fixed delay when the test can wait for a meaningful page condition.
Cookie injection only configures browser storage. It does not guarantee that a remote server will accept a session, that a site will render consistently, or that the page has finished loading. Keep test credentials scoped and avoid logging sensitive cookie values.
6. Capture a page after setting cookies
If your goal is to inspect the rendered page after a consent or preference cookie is set, use Puppeteer to establish the browser state and then capture the page in that same context. For a one-off website screenshot without configuring a browser, ScreenshotNeo is a website screenshot API and MCP server for developers. Its screenshot request does not expose Puppeteer’s cookie-injection flow, so use the browser method above when a test requires a specific cookie value.
Or skip the browser setup
For a screenshot of a public page, ScreenshotNeo returns an image or PDF from one GET request. Its API documentation lists the available parameters and formats.
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}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
const fs = require('node:fs');
fs.writeFileSync('shot.webp', Buffer.from(await res.arrayBuffer()));
- Cookie banners are accepted like a visitor, and cookie banners, newsletter popups, and chat widgets are removed before the shot; each step can be turned off.
- Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing. Responses identify the page verdict and billing status in headers.
- An MCP server gives AI agents, including Claude and Cursor, the tools
take_screenshot,get_page_info, andcapture_pdf. - The free plan includes 1,000 screenshots a month with no card. Paid plans start at $5 for 3,000 screenshots; yearly billing gives two months free, and every feature is on every plan.
Sign up for ScreenshotNeo and get 1,000 screenshots a month free, with no card required.
7. Frequently asked questions
Can I use CookieParam to log in to any website?
No. CookieParam describes browser cookie data. Whether a site accepts a supplied value depends on that site’s session and authentication behavior.
Should I set every optional property?
No. Set the fields needed to represent the cookie’s actual scope, lifetime, and behavior. Unnecessary or mismatched attributes can make a test less representative.
Does url replace domain and path?
A URL can influence defaults for domain, path, and source scheme. Use explicit scope fields when your test needs to specify them directly, and verify against the destination page.
Can I use a screenshot API to test cookie-dependent authentication?
Use a browser context when the test depends on setting a particular cookie value or verifying authenticated behavior. A screenshot API is useful for capturing a public page without managing browser setup.


