ScreenshotNeo

BlogHow-to

How to Fix “Puppeteer Is Not a Constructor” in puppeteer-web

Fix “Puppeteer is not a constructor” by matching your import, runtime, and browser bundle. Includes Node, browser, and Chrome extension solutions.

By the ScreenshotNeo team30 September 20269 min read

How to Fix “Puppeteer Is Not a Constructor” in puppeteer-web

“Puppeteer is not a constructor” usually means your code is instantiating an internal class or loading the Node package in a browser or Chrome extension runtime. In normal Node.js code, import Puppeteer’s exported instance and call launch() or connect(). In a browser page or extension, build a browser-compatible bundle from the browser entrypoint in puppeteer-core and connect to an existing browser endpoint or extension transport.

The fix depends on where the code runs. This guide covers the current supported paths, the historical puppeteer-web setup that causes confusion, complete examples, extension limitations, troubleshooting, and an API alternative when you only need screenshots.

What the error means

Puppeteer exposes a common API object, but application code is not meant to construct the base Puppeteer class. The official API reference marks its constructor as internal and says third-party code should use the exported API instead. The Node package gives you a PuppeteerNode instance, which extends that common API. In other words, this is wrong:

const Puppeteer = require('puppeteer');
const browser = new Puppeteer();

Use the instance returned by the package:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({ headless: true });
  const page = await browser.newPage();
  await page.goto('https://example.com', { waitUntil: 'networkidle2' });
  console.log(await page.title());
  await browser.close();
})();

With ECMAScript modules:

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
await page.goto('https://example.com', { waitUntil: 'networkidle2' });
console.log(await page.title());
await browser.close();

See the official Puppeteer API reference for the constructor rule and exported methods.

First, identify your runtime

Before changing code, determine whether the failing line runs in Node.js, a normal browser page, or a Chrome extension. The same package name resolves differently in these environments.

The correct Puppeteer entrypoint depends on whether code runs in Node, a browser page, or an extension.
The correct Puppeteer entrypoint depends on whether code runs in Node, a browser page, or an extension.
Runtime Use Browser connection Status
Node.js script or server puppeteer or puppeteer-core launch() or connect() Standard Puppeteer path
Normal browser page Bundled puppeteer-core/lib/puppeteer/puppeteer-core-browser.js connect() with a browser WebSocket endpoint Browser bundle required
Chrome extension Browser entrypoint from puppeteer-core ExtensionTransport.connectTab(tab.id) Experimental; one page per connection

If your stack trace mentions background.html, a content script, or an extension bundle, do not apply the Node import unchanged. If the code is server-side, remove any new Puppeteer() call and use the package instance.

Fix 1: Node.js

CommonJS

const puppeteer = require('puppeteer');

async function main() {
  const browser = await puppeteer.launch({
    headless: true,
    args: ['--no-sandbox']
  });

  try {
    const page = await browser.newPage();
    await page.setViewport({ width: 1440, height: 900, deviceScaleFactor: 1 });
    await page.goto('https://example.com', {
      waitUntil: 'networkidle2',
      timeout: 30_000
    });
    await page.screenshot({ path: 'example.png', fullPage: true });
  } finally {
    await browser.close();
  }
}

main().catch(error => {
  console.error(error);
  process.exitCode = 1;
});

ES modules

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch({ headless: true });
try {
  const page = await browser.newPage();
  await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
  console.log(await page.title());
} finally {
  await browser.close();
}

Using an existing browser

Use connect() when Chrome is already running with remote debugging enabled. Do not construct Puppeteer yourself.

const puppeteer = require('puppeteer-core');

(async () => {
  const browser = await puppeteer.connect({
    browserWSEndpoint: process.env.BROWSER_WS_ENDPOINT
  });
  const pages = await browser.pages();
  const page = pages[0] || await browser.newPage();
  await page.goto('https://example.com');
  await browser.disconnect();
})();

Fix 2: a normal browser page

The Node package is not a drop-in browser script. A browser cannot load Node-only modules, filesystem code, or the default Node entrypoint. Create a bundle with your build tool and import the browser entrypoint:

import puppeteer from 'puppeteer-core/lib/puppeteer/puppeteer-core-browser.js';

const browser = await puppeteer.connect({
  browserWSEndpoint: 'ws://localhost:9222/devtools/browser/YOUR_ID'
});
const pages = await browser.pages();
const page = pages[0] || await browser.newPage();
await page.goto('https://example.com');
console.log(await page.title());
await browser.disconnect();

The WebSocket endpoint must come from a browser that exposes the DevTools Protocol. A page cannot launch a local Chrome process by itself. Configure your bundler to emit browser code, then serve the resulting bundle from your application. The Puppeteer browser guide describes this browser-specific connection model.

Fix 3: Chrome extension

Puppeteer’s extension support is experimental because extensions access the DevTools Protocol through the restricted chrome.debugger API. Follow the extension-specific bundle and transport flow instead of loading the old puppeteer-web.js file directly.

Install and bundle the browser entrypoint

npm install puppeteer-core
npm install --save-dev esbuild

Example source module:

import puppeteer from 'puppeteer-core/lib/puppeteer/puppeteer-core-browser.js';
import { ExtensionTransport } from 'puppeteer-core/lib/puppeteer/common/ExtensionTransport.js';

export async function captureTab(tabId) {
  const transport = await ExtensionTransport.connectTab(tabId);
  const browser = await puppeteer.connect({ transport });

  try {
    const pages = await browser.pages();
    const page = pages[0];
    if (!page) throw new Error('No page is available for this tab');

    await page.screenshot({
      path: 'tab.png',
      fullPage: true
    });
  } finally {
    await browser.disconnect();
  }
}

Bundle it for the extension with a browser-aware tool. A minimal esbuild command is:

npx esbuild src/background.js \
  --bundle \
  --format=esm \
  --platform=browser \
  --outfile=dist/background.js

Your manifest needs the permissions required by your extension, including access to the tabs you intend to inspect and the debugger API required by the transport. Follow the current official Chrome extensions guide for the manifest details and supported bundling setup.

The one-page limitation

A connection created with ExtensionTransport.connectTab(tab.id) represents one page. To work with another tab, query it with chrome.tabs, create another transport, and connect again. Do not assume that browser.newPage() creates an independent extension-controlled tab in this mode.

async function captureActiveTab() {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  if (!tab || tab.id === undefined) {
    throw new Error('No active tab');
  }
  return captureTab(tab.id);
}

Why the old puppeteer-web example fails

The historical report that popularized this error loaded puppeteer/utils/browser/puppeteer-web.js in an extension page and separately required puppeteer from the background script. That setup mixed an old browser bundle with a Node-oriented package import. Its accepted answer suggested changing extension policy to allow unsafe-eval; treat that as historical context for the 2018 environment, not as the current general fix. Current guidance uses the browser entrypoint and extension transport.

Import and bundler checklist

  1. Print or inspect the imported value. Confirm it has methods such as launch, connect, or executablePath.
  2. Search your project for new Puppeteer, new puppeteer, and default-versus-named import mismatches.
  3. Check whether your package uses CommonJS or ESM. A default import may be nested under .default when interop is misconfigured.
  4. Verify the resolved package path with require.resolve('puppeteer') in Node.
  5. Delete the bundler cache and rebuild after changing the entrypoint.
  6. Make sure only one Puppeteer major version is being bundled.
  7. In an extension, confirm the generated file is the file referenced by the manifest.
  8. Capture the complete stack trace. The first project file in the trace usually reveals whether the failure happens during import, construction, or browser connection.

Troubleshooting common errors

Error or symptom Likely cause Fix
Puppeteer is not a constructor The exported instance or internal class is being called with new. Use puppeteer.launch() or puppeteer.connect().
puppeteer.launch is not a function Wrong import shape, often CommonJS/ESM interop. Inspect the value; try the package’s documented default import for your module type.
require is not defined Node code was loaded directly in a browser or extension. Bundle the browser entrypoint and remove Node-only imports.
Cannot find module ... puppeteer-web An old internal path is no longer present in the installed package. Use puppeteer-core/lib/puppeteer/puppeteer-core-browser.js and the current transport.
WebSocket connection fails The endpoint is missing, expired, blocked, or points to a non-debugging port. Obtain a valid browser WebSocket endpoint and test connectivity from the bundle’s runtime.
Extension connects but has no page The tab has no inspectable page or the connection targets the wrong tab. Query the tab again, check its ID, and handle an empty browser.pages() result.
Only one extension page works The documented extension transport represents one page. Create a separate connection for each tab.
Blank screenshot or navigation timeout The page is still loading, blocked, or requires authentication. Use an explicit wait condition, inspect console and network errors, and set a realistic timeout.

Reliability and performance practices

  • Reuse Node browsers. Launching Chrome for every request adds startup cost. Keep a browser process alive and create or close pages per job.
  • Always close or disconnect. Use try/finally so failed navigation does not leak pages or browser processes.
  • Choose waits deliberately. domcontentloaded is faster than networkidle2; use a selector wait when the screenshot depends on one component.
  • Bound every operation. Set navigation, selector, and overall job timeouts. A retry should create a clear new attempt rather than duplicating an in-flight capture.
  • Control concurrency. Too many pages compete for CPU, memory, and network bandwidth. Use a queue and a fixed worker count.
  • Record the runtime context. Log package versions, resolved entrypoint, browser version, target URL, and the exact wait condition.
  • Use deterministic inputs. Set viewport, timezone, locale, user agent, and authentication consistently when comparing screenshots.
A screenshot service can handle consent banners and overlays before capture.
A screenshot service can handle consent banners and overlays before capture.

Or skip the browser setup

If your goal is a clean screenshot rather than browser automation, ScreenshotNeo provides a single HTTP request. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; response headers identify the page verdict and billing result.

See the ScreenshotNeo API documentation for all options. The basic request works from any environment:

cURL

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

Node.js

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 failed: ${res.status}`);
const buffer = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('shot.webp', buffer);

ScreenshotNeo also supports PNG, JPEG, and PDF output; full-page captures with lazy images loaded; element selection; dark mode; device presets and custom viewports; retina scale; custom CSS and JavaScript; clicks; selector or network-idle waits; request blocking; headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, configurable caching, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

There is a free plan with 1,000 screenshots per month and no card. Paid plans start at $5 for 3,000 screenshots; yearly billing gives two months free, and every feature is available on every plan. Create a free ScreenshotNeo account.

Cost considerations

Self-hosted Puppeteer costs the infrastructure required to run Chrome: CPU, memory, storage, browser maintenance, queueing, and engineering time for retries and cleanup. A hosted API trades that setup for per-shot billing. With ScreenshotNeo, only clean shots are billed, while failed loads, bot checks, blank pages, timeouts, and cache hits are free. Inspect X-Page-Verdict and X-Billed in responses when reconciling usage.

FAQ

Can I fix this by installing a different Puppeteer version?

Possibly, but version changes do not correct an invalid constructor call or a Node bundle loaded in an extension. First fix the runtime and import. Upgrade or downgrade only when your project has a verified compatibility requirement.

Should I use puppeteer or puppeteer-core?

Use puppeteer when you want the Node package’s managed browser workflow. Use puppeteer-core when connecting to an existing browser or producing a browser or extension bundle.

Does connect() launch Chrome?

No. It attaches to a browser that is already running and exposes a valid connection endpoint or transport.

Is unsafe-eval required?

Do not add it as a default remedy. The historical answer came from an older extension setup. Current extension guidance uses a browser-compatible bundle and ExtensionTransport.

Why does my extension see only one page?

That is a documented limitation of the extension transport connection. Query another tab and establish a separate connection for it.