ScreenshotNeo

BlogHow-to

Puppeteer Cookies: Read and Set Cookies in a Browser

Read, set, and clean up cookies in Puppeteer with the current Browser and BrowserContext APIs, including isolated test contexts and common fixes.

By the ScreenshotNeo team4 October 20267 min read

Puppeteer’s current cookie APIs are browser.cookies() and browser.setCookie(...cookies) for the default browser context, or context.cookies() and context.setCookie(...cookies) for a specific BrowserContext. Set cookies before navigation when the page needs them on its first request. Use the same context to set, read, and clean up state. The older page.cookies() and page.setCookie() methods are deprecated.

This guide uses Puppeteer’s current JavaScript API. The examples use ES modules; on older Node.js projects, configure the package for ES modules or adapt the import to your project’s module system. Puppeteer’s documentation describes storing and restoring cookies as useful for tests. See the Puppeteer cookies guide and the Browser.cookies() reference.

1. Read cookies from the default browser context

Launch Puppeteer, navigate to the site whose cookies you want to inspect, then read the default context’s cookies:

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();
try {
  const page = await browser.newPage();
  await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });

  const cookies = await browser.cookies();
  console.log(cookies);
} finally {
  await browser.close();
}

browser.cookies() reads cookies in the default BrowserContext. In practical terms, navigate first when you want to inspect cookies the site creates during loading or after an interaction. Browser contexts isolate storage; cookies from another context will not appear in this result. Reference: Puppeteer Browser.cookies().

Cookie values can contain authentication material. Avoid logging them in shared CI output or committing captured cookie data to source control. For debugging, log only the fields you need, such as names and domains.

2. Set cookies before navigation

Call browser.setCookie(...cookies) before page.goto() when the first navigation should carry the cookie. The cookie’s domain and security attributes must fit the site under test.

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();
try {
  const page = await browser.newPage();

  await browser.setCookie({
    name: 'theme',
    value: 'dark',
    domain: 'example.com',
    path: '/',
    httpOnly: false,
    secure: true,
    sameSite: 'Lax',
  });

  await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
  console.log(await browser.cookies());
} finally {
  await browser.close();
}

Browser.setCookie() sets cookies in the default context. Its arguments are cookie data objects; see the Browser.setCookie() API reference and the CookieData interface.

Field Use
name, value The cookie name and stored value. Both are required.
domain The cookie’s domain. Required by CookieData; use a domain appropriate for the target site.
path Limits the URL paths for which the cookie applies. Set / when it should cover the site’s paths.
expires Optional expiration time. With no expiry, the cookie is a session cookie according to the interface description.
httpOnly Boolean attribute for cookies intended to be inaccessible to page JavaScript.
secure Boolean attribute for cookies intended for secure connections. Match it to the URL and test environment.
sameSite SameSite setting, using the values documented by Puppeteer’s cookie type and supported by the target browser.
partitionKey Partition key for partitioned cookies. Its description and support vary by browser; check the API reference for the browser you use.

The interface documents these properties, but browser support and behavior can differ for some fields. Consult CookieData and avoid assuming that a cookie accepted in one browser has identical behavior in another.

Create a dedicated context when a test, account, or scenario needs separate cookies and local storage. Set and inspect cookies on that context so the operations apply to the same isolated store.

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();
const context = await browser.createBrowserContext();
try {
  const page = await context.newPage();

  await context.setCookie({
    name: 'test-session',
    value: 'scenario-a',
    domain: 'example.com',
    path: '/',
    secure: true,
    httpOnly: true,
    sameSite: 'Lax',
  });

  await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
  const cookies = await context.cookies();
  console.log(cookies.map(({ name, domain }) => ({ name, domain })));
} finally {
  await context.close();
  await browser.close();
}

Each BrowserContext has isolated cookies and local storage. Browser-level cookie methods are shortcuts for the default context; context methods operate on the context you chose. If multiple tests need independent sessions, give each one its own context rather than sharing a single cookie store. See the BrowserContext.setCookie() reference and Puppeteer API reference.

4. Remove cookies during test cleanup

For simple cleanup, close the dedicated context after the test. Its isolated storage is discarded with it. If you need to remove cookies while retaining the context, use the current cookie APIs to inspect the store and set an expired value for the cookie you want to remove, following the cookie API’s accepted data shape. The cookies guide demonstrates deletion as part of cookie management.

const cookies = await context.cookies();
console.log(cookies.map(({ name, domain }) => ({ name, domain })));

// Prefer closing a disposable test context when the scenario is complete.
await context.close();

For reusable contexts, make cleanup part of the test fixture and verify the resulting cookie list. Avoid clearing a shared default context if other tests depend on its state.

5. Why page.cookies() and page.setCookie() are deprecated

Puppeteer’s Page API marks Page.cookies() and Page.setCookie() obsolete and directs users to browser-level or context-level methods. Update new code to use browser.cookies()/browser.setCookie(...) for the default context, or context.cookies()/context.setCookie(...) for an explicit context. The old methods remain useful to recognize in existing code, but should not be the pattern for new code. References: Page.cookies() and Page.setCookie().

6. Do-it-yourself checklist

  1. Choose the storage owner: default browser context or a dedicated BrowserContext.
  2. Set cookies on that owner before navigation if the initial request needs them.
  3. Use a domain, path, and secure setting that match the target origin.
  4. Navigate or perform the interaction that causes the site to create cookies.
  5. Read cookies from the same browser or context object used for setup.
  6. Close disposable contexts after the test and keep cookie secrets out of logs.

7. Common errors and fixes

Symptom Likely cause Fix
Cookie is missing after setting it The code reads a different context from the one where the cookie was set. Use the same BrowserContext for setting, navigation, and reading, or use browser methods consistently for the default context.
Cookie does not appear on the first request It was set after navigation, or its domain/path does not match the requested URL. Set it before page.goto(); check the domain and path against the target site.
Secure cookie is not sent on a local HTTP URL The cookie’s secure setting and test URL may not fit. Use HTTPS for secure-cookie behavior, or configure the test cookie for the actual local environment.
Cookie exists in browser output but page JavaScript cannot read it httpOnly is enabled. That attribute is intended to keep the cookie inaccessible to page JavaScript; inspect it through Puppeteer’s cookie API instead.
Deprecated API warning or migration issue Existing code calls page.cookies() or page.setCookie(). Move to browser.cookies()/browser.setCookie(...) or the corresponding methods on the owning context.
Partitioned cookie behavior differs between browsers partitionKey support and descriptions are browser-specific. Check the current CookieData documentation for the browser under test and test that browser directly.
Cookie disappears between test cases Each case uses a fresh isolated context, or the context was closed. Seed the cookie in each test’s context, or intentionally reuse a context when shared state is part of the test design.

8. Performance, reliability, and cost

Cookie reads and writes are small browser storage operations; the larger reliability decision is context ownership. A fresh context gives tests isolated state, while deliberate reuse can preserve a session between steps. Keep setup and teardown explicit so test order does not silently determine authentication state. Puppeteer does not document a numeric performance guarantee for these calls in the cited references, so measure your own end-to-end test flow if timing matters.

Running Puppeteer means managing a browser process, navigation, and test environment. Browser launch and page loading usually dominate the work around cookie operations. For repeatable tests, use a consistent browser version and explicit waits rather than arbitrary delays where possible. Cost depends on where and how you run the browser; the Puppeteer documentation cited here does not specify hosting prices.

9. Or skip the browser setup

If your goal is a screenshot rather than controlling test storage, ScreenshotNeo is a website screenshot API and MCP server from Yorker Media. A GET request returns a PNG, JPEG, WebP, or PDF. See the ScreenshotNeo API 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}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
await Bun.write('shot.webp', res);

ScreenshotNeo removes cookie banners, popups, and chat widgets before the shot. Bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots. The Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots. These are screenshot captures, not a replacement for Puppeteer tests that need to set application cookies. Sign up for 1,000 free screenshots a month, with no card.

10. FAQ

How do I get cookies in Puppeteer?

Navigate using the target page, then call browser.cookies() for the default context or context.cookies() for the context that owns the page.

Call browser.setCookie(cookie) or context.setCookie(cookie) before page.goto(), and make the cookie domain and security attributes fit the destination.

Why is page.setCookie() deprecated?

Puppeteer marks the Page method obsolete and directs callers to the Browser or BrowserContext cookie APIs, which align cookie access with the storage context that owns the state.

Can I use browser.cookies() for an isolated context?

No. That method reads the default context. Call context.cookies() on the isolated context instead.