Allscreenshots
Sign inGet an API key
Blog

Guide

What is Puppeteer and How Does It Work?

Alex Chen13 min read

Puppeteer is a JavaScript library for controlling real browsers from code. Instead of opening Chrome, clicking buttons, typing into forms, waiting for pages to load, and saving screenshots manually, you describe those actions in Node.js and Puppeteer performs them through an automated browser.

At a beginner level, Puppeteer is useful because it makes browser automation approachable. You can install one package, write a short script, and capture a screenshot or scrape rendered content from a JavaScript-heavy page.

At an advanced level, Puppeteer is useful because it exposes browser internals that normal HTTP clients cannot reach: network requests, cookies, frames, execution contexts, browser profiles, console messages, performance traces, PDF rendering, and DevTools-level debugging hooks.

What Puppeteer is

Puppeteer is a high-level API over browser automation protocols. It runs in Node.js, launches or connects to a browser, opens pages, and sends commands to those pages.

You can use Puppeteer for:

  • Website screenshots and full-page captures
  • PDF generation from rendered HTML
  • End-to-end smoke tests
  • Web scraping pages that require JavaScript
  • Form automation and repetitive browser workflows
  • Network inspection, mocking, and request blocking
  • Performance analysis and debugging
  • Visual regression test capture

The key phrase is rendered browser automation. Puppeteer is not just downloading HTML. It is controlling a real browser engine, so the page can run JavaScript, load CSS, execute client-side routing, render canvas, apply fonts, and behave much closer to what a user sees.

What Puppeteer is not

Puppeteer is powerful, but it is easy to overuse if you treat it as the default answer for every web automation problem.

Puppeteer is not a general HTTP scraping library. If a site returns all the data you need in static HTML or JSON, fetch, axios, or a dedicated API client will usually be faster, cheaper, and simpler.

Puppeteer is not a complete test runner by itself. It can drive the browser, but it does not provide the full structure of a testing framework: assertions, retries, reporters, parallel test orchestration, fixtures, and project configuration. You can pair it with Jest, Mocha, or Vitest, but tools like Playwright Test include more testing infrastructure out of the box.

Puppeteer is not a magic way around bot detection. It controls a browser, but websites can still rate-limit requests, require authentication, fingerprint automation, or block suspicious behavior. Use it for legitimate automation, respect site terms, and avoid collecting data you do not have permission to access.

How Puppeteer works

The simplest mental model looks like this:

md
Your Node.js script -> Puppeteer API -> Browser automation protocol -> Chrome or Firefox -> Web page

You call methods such as page.goto(), page.click(), and page.screenshot(). Puppeteer converts those method calls into protocol messages. The browser receives those messages, performs the action, and sends results or events back to Puppeteer.

With Chrome, Puppeteer uses the Chrome DevTools Protocol by default. This is the same family of browser capabilities behind Chrome DevTools. That is why Puppeteer can inspect network traffic, listen to console logs, generate PDFs, access performance data, and create DevTools protocol sessions.

With Firefox, Puppeteer uses WebDriver BiDi by default. WebDriver BiDi is a newer browser automation protocol designed for bidirectional communication between automation clients and browsers. Puppeteer can also use WebDriver BiDi with Chrome, although Chrome still defaults to CDP because some Puppeteer features remain CDP-specific.

The browser lifecycle

Most Puppeteer scripts follow the same lifecycle:

  1. Launch or connect to a browser
  2. Create a page
  3. Configure the page
  4. Navigate to a URL
  5. Wait for the right state
  6. Interact with the page or extract data
  7. Save output
  8. Close the page or browser

Here is the smallest useful example:

javascript
import puppeteer from 'puppeteer'; const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://example.com'); await page.screenshot({ path: 'example.png' }); await browser.close();

That script launches a browser, opens a tab, navigates to a page, captures the viewport, and closes the browser process.

For local debugging, run the browser in headful mode:

javascript
const browser = await puppeteer.launch({ headless: false, slowMo: 50, });

headless: false shows the browser window. slowMo adds a small delay between operations, which makes it easier to see what your script is doing.

The core objects

Puppeteer code becomes much easier to understand once you know the main objects.

ObjectWhat it representsCommon use
BrowserA running browser processLaunching pages, creating contexts, closing the browser
BrowserContextAn isolated browser sessionSeparate cookies, local storage, permissions, and cache
PageA browser tabNavigation, clicks, typing, screenshots, evaluation
FrameA document inside a pageWorking with iframes
ElementHandleA reference to a DOM elementClicking, typing, reading properties, element screenshots
JSHandleA reference to a JavaScript valuePassing browser-side values back to Node.js

Most scripts spend nearly all their time working with Page.

javascript
const browser = await puppeteer.launch(); const context = await browser.createBrowserContext(); const page = await context.newPage(); await page.goto('https://example.com'); await context.close(); await browser.close();

Browser contexts are useful when you need isolation. For example, a test suite can create a fresh context per test so cookies and local storage do not leak between runs.

Browser automation fails most often because the script acts before the page is ready. Puppeteer gives you explicit waiting tools, but you still need to choose the right condition.

javascript
await page.goto('https://example.com', { waitUntil: 'domcontentloaded', }); await page.waitForSelector('main');

The common navigation wait options are:

OptionMeaningBest for
loadWait for the browser load eventTraditional pages
domcontentloadedWait for the initial HTML document to be parsedFast scripts that do their own follow-up waits
networkidle0Wait until there are no network connections for a short periodPages that finish loading cleanly
networkidle2Wait until there are no more than two network connectionsSPAs with some background requests

Do not blindly use networkidle0 everywhere. Some apps keep analytics, live updates, or long-polling requests open. In those cases, a selector or app-specific condition is more reliable.

javascript
await page.goto('https://app.example.com/dashboard'); await page.waitForSelector('[data-testid="dashboard-ready"]');

For advanced flows, wait for a specific network response:

javascript
const responsePromise = page.waitForResponse((response) => response.url().includes('/api/products') && response.status() === 200 ); await page.click('[data-testid="load-products"]'); const response = await responsePromise; const data = await response.json();

That pattern avoids arbitrary sleeps. The script continues when the real dependency has completed.

Selecting and interacting with elements

Puppeteer can interact with elements using CSS selectors, XPath-style selectors, and richer selector syntax. CSS selectors are the most common:

javascript
await page.click('button[type="submit"]'); await page.type('input[name="email"]', '[email protected]'); await page.select('select[name="country"]', 'US');

For content extraction, use page.$eval() for one element and page.$$eval() for many elements:

javascript
const title = await page.$eval('h1', (element) => element.textContent); const links = await page.$$eval('a', (anchors) => anchors.map((anchor) => ({ text: anchor.textContent?.trim(), href: anchor.href, })) );

The function passed to $eval() runs inside the browser, not in Node.js. That means it can access DOM APIs such as document, window, getComputedStyle, and element properties. It cannot directly access Node.js variables unless you pass them as arguments.

javascript
const minimumLength = 10; const headings = await page.$$eval( 'h2', (elements, min) => elements .map((element) => element.textContent?.trim() ?? '') .filter((text) => text.length >= min), minimumLength );

Running code in the page

page.evaluate() is one of Puppeteer's most important APIs. It lets you execute JavaScript in the page context and return serializable data to Node.js.

javascript
const pageInfo = await page.evaluate(() => { return { title: document.title, url: location.href, headings: Array.from(document.querySelectorAll('h1, h2')).map((heading) => heading.textContent?.trim() ), }; });

This is useful for scraping, diagnostics, layout inspection, and extracting application state from rendered pages.

There are two important boundaries:

  1. Browser-side code can access the DOM, but not Node.js APIs like fs.
  2. Returned values must be serializable, so DOM nodes become handles or need to be converted into plain objects.

If you need to pass data from Node.js into the page, provide it as an extra argument:

javascript
const selector = '.product-card'; const count = await page.evaluate((cardSelector) => { return document.querySelectorAll(cardSelector).length; }, selector);

Screenshots and PDFs

Puppeteer is widely used for visual output because it captures what the browser actually renders.

javascript
await page.setViewport({ width: 1440, height: 900, deviceScaleFactor: 2, }); await page.goto('https://example.com', { waitUntil: 'networkidle2', }); await page.screenshot({ path: 'homepage.png', fullPage: true, });

You can also capture a single element:

javascript
const hero = await page.waitForSelector('.hero'); await hero.screenshot({ path: 'hero.png' });

PDF generation uses Chrome's print pipeline:

javascript
await page.pdf({ path: 'report.pdf', format: 'A4', printBackground: true, margin: { top: '24px', right: '24px', bottom: '24px', left: '24px', }, });

For production screenshots, consistency matters. Set the viewport, device scale factor, color scheme, authentication state, and wait conditions deliberately. Small environment differences can create different visual results.

Network control

Puppeteer can observe and modify network activity. This is one of the biggest differences between browser automation and simple page fetching.

Listen to requests and responses:

javascript
page.on('request', (request) => { console.log('Request:', request.method(), request.url()); }); page.on('response', (response) => { console.log('Response:', response.status(), response.url()); });

Block resource types to speed up scraping:

javascript
await page.setRequestInterception(true); page.on('request', (request) => { const blockedTypes = new Set(['image', 'font', 'media']); if (blockedTypes.has(request.resourceType())) { request.abort(); return; } request.continue(); });

Mock an API response for testing:

javascript
await page.setRequestInterception(true); page.on('request', (request) => { if (request.url().endsWith('/api/account')) { request.respond({ status: 200, contentType: 'application/json', body: JSON.stringify({ plan: 'pro', seats: 5, }), }); return; } request.continue(); });

Network interception is useful for test determinism, performance, scraping optimization, and reproducing edge cases. It can also make scripts fragile if you intercept too broadly, so keep matching rules specific.

Headless, headful, and browser binaries

Puppeteer can run without a visible browser window. That is headless mode, and it is the default choice for CI and server automation.

javascript
const browser = await puppeteer.launch({ headless: true, });

Headful mode shows the browser:

javascript
const browser = await puppeteer.launch({ headless: false, });

By default, the full puppeteer package downloads a compatible browser during installation. Current releases download Chrome for Testing for Chrome automation and can download stable Firefox for Firefox automation. This avoids the old Selenium-style problem of manually matching a driver version to a browser version.

If you do not want Puppeteer to download a browser, use puppeteer-core and provide your own executable path:

javascript
import puppeteer from 'puppeteer-core'; const browser = await puppeteer.launch({ executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', });

Use puppeteer when you want the package to manage browser downloads. Use puppeteer-core when you are deploying into an environment that already has a browser installed or you are connecting to a remote browser service.

Chrome, Firefox, CDP, and WebDriver BiDi

Puppeteer's browser support has changed over time, so older articles can be misleading.

BrowserCurrent Puppeteer supportDefault protocol
ChromeSupportedChrome DevTools Protocol
FirefoxSupportedWebDriver BiDi
SafariNot a Puppeteer targetNot applicable

Chrome remains Puppeteer's strongest fit because CDP gives deep access to Chrome internals. Some features, such as CDP sessions, tracing, coverage, and certain emulation APIs, are tied to CDP.

Firefox support is important when you need browser coverage beyond Chrome, but WebDriver BiDi support does not mean every Puppeteer feature behaves identically across browsers. If you need broad cross-browser end-to-end testing, compare Puppeteer with Playwright before committing to a test architecture.

To launch Firefox:

javascript
const browser = await puppeteer.launch({ browser: 'firefox', });

To use WebDriver BiDi with Chrome:

javascript
const browser = await puppeteer.launch({ browser: 'chrome', protocol: 'webDriverBiDi', });

For most Chrome automation, keep the default CDP protocol unless you specifically need to test WebDriver BiDi behavior.

Debugging Puppeteer scripts

When a script fails, make the browser visible and collect evidence.

javascript
const browser = await puppeteer.launch({ headless: false, devtools: true, slowMo: 100, });

Capture a screenshot when something goes wrong:

javascript
try { await page.click('[data-testid="checkout"]'); } catch (error) { await page.screenshot({ path: 'debug-checkout.png', fullPage: true }); throw error; }

Log browser console output:

javascript
page.on('console', (message) => { console.log(`Browser console ${message.type()}: ${message.text()}`); });

Log page errors:

javascript
page.on('pageerror', (error) => { console.error('Page error:', error.message); });

For advanced debugging, connect to a running browser using a remote debugging endpoint or create a CDP session:

javascript
const client = await page.createCDPSession(); await client.send('Performance.enable'); const metrics = await client.send('Performance.getMetrics'); console.log(metrics);

That kind of low-level access is one reason advanced users still reach for Puppeteer when they need Chrome-specific instrumentation.

Common beginner mistakes

Closing the browser too late or too early

Always close browser resources, especially in scripts that run repeatedly.

javascript
const browser = await puppeteer.launch(); try { const page = await browser.newPage(); await page.goto('https://example.com'); } finally { await browser.close(); }

Without finally, a thrown error can leave browser processes running.

Using selectors that change constantly

Auto-generated class names are poor selectors:

javascript
await page.click('.css-1abcxyz');

Prefer stable attributes when you control the app:

javascript
await page.click('[data-testid="submit-order"]');

For scraping, choose semantic structure where possible:

javascript
const prices = await page.$$eval('[itemprop="price"]', (elements) => elements.map((element) => element.textContent?.trim()) );

Assuming page HTML contains rendered data

Modern apps often render content after API calls. If you read the page too early, you get empty containers.

javascript
await page.goto('https://example.com/products'); await page.waitForSelector('.product-card'); const products = await page.$$eval('.product-card', (cards) => cards.map((card) => card.textContent?.trim()) );

Reusing a single page forever

Long-running jobs should periodically create fresh pages or contexts. Browsers accumulate memory, event listeners, cache, and application state. For batch automation, isolate each unit of work:

javascript
for (const url of urls) { const page = await browser.newPage(); try { await page.goto(url, { waitUntil: 'domcontentloaded' }); await page.screenshot({ path: createFilename(url) }); } finally { await page.close(); } }

Advanced patterns

Reusing authentication state

Logging in through the UI for every script run is slow and brittle. One approach is to save cookies after login and reuse them.

javascript
import fs from 'node:fs/promises'; const browser = await puppeteer.launch({ headless: false }); const page = await browser.newPage(); await page.goto('https://app.example.com/login'); // Complete login manually or through automation. await page.waitForSelector('[data-testid="dashboard"]'); const cookies = await page.cookies(); await fs.writeFile('cookies.json', JSON.stringify(cookies, null, 2)); await browser.close();

Then load them in another run:

javascript
const cookies = JSON.parse(await fs.readFile('cookies.json', 'utf8')); const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.setCookie(...cookies); await page.goto('https://app.example.com/dashboard');

For more complete isolation, use a persistent user data directory, but be careful not to share it across concurrent jobs.

Parallelizing work

Launching a new browser for every URL is expensive. Opening too many pages in one browser can exhaust memory. A practical pattern is one browser with a small concurrency limit.

javascript
import puppeteer from 'puppeteer'; const urls = [ 'https://example.com', 'https://example.org', 'https://example.net', ]; const browser = await puppeteer.launch(); const concurrency = 3; let index = 0; async function worker() { while (index < urls.length) { const currentIndex = index; index += 1; const page = await browser.newPage(); try { await page.goto(urls[currentIndex], { waitUntil: 'domcontentloaded' }); await page.screenshot({ path: `capture-${currentIndex}.png` }); } finally { await page.close(); } } } await Promise.all(Array.from({ length: concurrency }, () => worker())); await browser.close();

Tune concurrency based on page weight and available memory. Heavy JavaScript apps may need low concurrency. Simple static pages can handle more.

Device and media emulation

Puppeteer can emulate viewport size, device scale, user agent, media type, and color scheme.

javascript
await page.setViewport({ width: 390, height: 844, isMobile: true, hasTouch: true, deviceScaleFactor: 3, }); await page.emulateMediaType('screen'); await page.emulateMediaFeatures([ { name: 'prefers-color-scheme', value: 'dark' }, ]);

This is useful for responsive screenshots, visual regression testing, print styles, and checking dark mode.

Connecting to a remote browser

In production, many teams avoid launching browsers inside every application process. Instead, they connect to a browser running in a separate container or managed service.

javascript
const browser = await puppeteer.connect({ browserWSEndpoint: 'wss://browser.example.com/session', }); const page = await browser.newPage(); await page.goto('https://example.com'); await page.screenshot({ path: 'remote.png' }); await browser.disconnect();

Remote browsers can simplify scaling, but they introduce network latency and operational concerns. Make sure you handle timeouts, authentication, and session cleanup.

Running Puppeteer in CI and production

Headless browsers are heavier than normal server-side code. A single browser can consume hundreds of megabytes depending on the page. Production Puppeteer systems need resource limits, retries, and cleanup.

For Linux containers, you may need system dependencies for Chrome. Some projects install Chrome directly and point Puppeteer at the system binary:

dockerfile
FROM node:22-slim RUN apt-get update && apt-get install -y \ chromium \ --no-install-recommends && \ rm -rf /var/lib/apt/lists/* ENV PUPPETEER_SKIP_DOWNLOAD=true ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . CMD ["node", "capture.js"]

In restricted containers, you may see examples using --no-sandbox:

javascript
const browser = await puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'], });

Only use those flags when your environment requires them and you understand the security trade-off. The browser sandbox exists for a reason.

Production checklist:

  • Set navigation and operation timeouts
  • Close pages in finally blocks
  • Limit concurrency
  • Capture debug screenshots on failure
  • Track browser memory usage
  • Restart long-lived browser processes periodically
  • Use stable browser versions
  • Avoid running untrusted pages with unnecessary permissions

Puppeteer vs Playwright vs Selenium

Puppeteer is one of several browser automation tools. The right choice depends on the job.

ToolBest fitTrade-off
PuppeteerChrome-first automation, screenshots, PDFs, scraping, DevTools-level controlLess complete as a test platform; Safari is not supported
PlaywrightModern cross-browser end-to-end testingLarger test framework and slightly more abstraction
SeleniumBroad language and browser ecosystem, legacy enterprise environmentsMore driver and infrastructure complexity

Choose Puppeteer when you want a focused Node.js API, deep Chrome integration, and direct control over browser behavior.

Choose Playwright when your main goal is reliable end-to-end testing across Chromium, Firefox, and WebKit with built-in assertions, tracing, and test orchestration.

Choose Selenium when your organization already depends on WebDriver infrastructure, needs broad language support, or must support older browser environments.

When Puppeteer is the right tool

Puppeteer is a strong fit when:

  • You need rendered output, not just raw HTML
  • You are automating Chrome-first workflows
  • You need screenshots or PDFs
  • You need network interception or browser console visibility
  • You need to run JavaScript in the page context
  • You need DevTools-level access for performance or diagnostics
  • Your team is comfortable with Node.js

It is a weaker fit when:

  • You only need static HTML
  • You need Safari automation
  • You need a complete test runner with minimal setup
  • You need large-scale scraping without browser-like behavior
  • Your workload cannot afford browser memory overhead

Skip the browser infrastructure for screenshots

Puppeteer is excellent when you need custom browser automation. But screenshot systems become operationally expensive quickly: browser dependencies, memory pressure, queueing, timeouts, retries, lazy-loaded content, device emulation, and noisy page elements all need attention.

For screenshot-specific workflows, AllScreenshots handles the browser infrastructure for you:

bash
curl -X POST 'https://api.allscreenshots.com/v1/screenshots' \ -H 'X-API-Key: your-api-key' \ -H 'Content-Type: application/json' \ -d '{"url": "https://example.com", "fullPage": true}'

Use Puppeteer when the browser behavior is part of your application logic. Use a screenshot API when you mainly need consistent captures without maintaining headless browser infrastructure.

Conclusion

Puppeteer works by turning Node.js code into browser protocol commands. That simple idea unlocks a lot: real page rendering, user-like interactions, screenshots, PDFs, network control, JavaScript execution, and access to browser internals.

For beginners, the best way to learn Puppeteer is to start with one page, one action, and one visible output. Navigate to a site, wait for a selector, capture a screenshot, then close the browser.

For advanced users, the value is in the edges: browser contexts for isolation, request interception for control, CDP sessions for deep Chrome instrumentation, remote browsers for scale, and careful concurrency management for production reliability.

Puppeteer is not the right tool for every web task. But when you need to automate what a real browser sees and does, it remains one of the most direct and capable options available.

Find out how easy it is to capture and share pixel-perfect screenshots at scale using Allscreenshots. Sign up for a free account and start integrating your first screenshot API call today.

Start with one request

Free plan: 100 screenshots. No credit card.

Get an API key
  • Full-page captures
  • Popups and repeated sticky bars removed
  • Markdown, JSON and PDF output
  • Crawl a site from one URL
  • Desktop, tablet and phone in one image
  • Works in n8n, Make and Zapier
  • MCP server for AI assistants