User Agents

Web browsers and everyday web tech, explained

Debug Puppeteer Browser Automation Layer by Layer

· 5 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Debugging Puppeteer scripts can feel like peeling an onion—each layer hides another potential failure point. This guide walks you through a systematic, layer-by-layer approach to identify and fix issues in your Puppeteer automation, from the simplest console logs to advanced network interception. You’ll learn how to isolate problems in the Node.js environment, the browser context, and the communication between them.

What You'll Need

  • A Node.js project with Puppeteer installed (npm install puppeteer)
  • A basic Puppeteer script that you want to debug
  • A code editor with a debugger (VS Code recommended)
  • Chrome DevTools knowledge (optional but helpful)

Step-by-Step

  1. Start with console logs in Node.js. Add console.log statements around your Puppeteer calls to see the order of execution and the values of variables. For example, log the URL before and after page.goto(), and log the result of any page.evaluate() calls.
  2. Enable Puppeteer's internal debugging. Set the environment variable DEBUG=puppeteer:* when running your script (e.g., DEBUG=puppeteer:* node script.js). This prints detailed logs about protocol commands, responses, and events, helping you see what the browser is actually doing.
  3. Run with headless: false and slowMo. Launch the browser with headless: false to watch the automation in real time. Add slowMo: 250 to slow down each operation by 250ms, making it easier to spot visual issues like wrong selectors or timing problems.
  4. Use page.on('console') to capture browser console logs. In your script, add page.on('console', msg => console.log('BROWSER LOG:', msg.text())). This forwards any console messages from the page (like console.log in your page's JavaScript) to your Node.js terminal, revealing errors that occur inside the page.
  5. Listen for page errors and request failures. Add page.on('pageerror', err => console.log('PAGE ERROR:', err.message)) to catch uncaught exceptions in the page. Also add page.on('requestfailed', req => console.log('REQ FAILED:', req.url(), req.failure()?.errorText)) to see network issues like blocked resources or failed navigations.
  6. Take screenshots at critical points. Use await page.screenshot({ path: 'step.png' }) after key actions (e.g., after page load, after clicking a button) to visually inspect the page state. Compare screenshots to see what changed or what didn't.
  7. Inspect the DOM with page.evaluate. Run small snippets like await page.evaluate(() => document.body.innerHTML) to see the actual HTML structure. This helps verify if selectors match the expected elements, especially when pages are dynamically rendered.
  8. Use page.waitForSelector with explicit timeouts. Replace arbitrary page.waitForTimeout calls with await page.waitForSelector('selector', { timeout: 5000 }). This waits for an element to appear, reducing flakiness and making the failure point clearer (it will throw a timeout error).
  9. Set up Node.js debugger breakpoints. In VS Code, create a launch.json configuration for Node.js, then set breakpoints in your script. Run with the debugger and step through each Puppeteer call, inspecting variables and the state of the browser.
  10. Use Chrome DevTools Protocol (CDP) directly. For deep debugging, call await page.createCDPSession() to send raw CDP commands. For example, session.send('Network.enable') and listen to Network.requestWillBeSent events to see all network requests in detail.
  11. Isolate the problem layer. If the script fails, determine if the issue is in the Node.js layer (your logic), the browser layer (page rendering/JS), or the communication layer (Puppeteer protocol). For example, if page.goto() times out, test if the URL loads in a normal browser. If it does, the issue may be with Puppeteer's network interception or proxy settings.
  12. Check the browser's DevTools console manually. When running with headless: false, open the browser's DevTools (F12) and inspect the console, network, and elements tabs. This gives you the same view as a human user, often revealing issues that Puppeteer's logs miss.

Common Mistakes

  • Using page.waitForTimeout() for fixed delays—this is unreliable; use waitForSelector or waitForFunction instead.
  • Not awaiting Puppeteer calls—forgetting await on page.goto(), page.click(), etc., can cause race conditions.
  • Assuming the page is fully loaded after goto()—single-page apps often load content asynchronously; wait for the specific element you need.
  • Ignoring the browser console—many errors are only visible there, not in the Node.js output.

Tips

  • Use a helper function to wrap common actions with logging, e.g., async function click(selector) { console.log('Clicking', selector); await page.click(selector); }.
  • Keep a screenshot directory to store screenshots at each step; this helps compare runs.
  • Use page.setDefaultTimeout() to set a global timeout for all wait operations, reducing the chance of hanging.
  • For complex selectors, test them in the browser console first using document.querySelector.

Troubleshooting

If your script still fails after following these steps, try the following:

  • Update Puppeteer to the latest version—bugs are often fixed in new releases.
  • Check the browser version—Puppeteer bundles a compatible Chrome version; if you're using a system Chrome, ensure it's not too old or too new.
  • Disable headless mode temporarily to see if the issue only occurs in headless (some sites behave differently).
  • Test with a minimal script—create a simple script that just opens a blank page and logs document.title. If that works, gradually add parts of your original script to isolate the breaking section.
  • Look for anti-bot measures—some sites use Cloudflare or similar; you may need to add page.setUserAgent() or use puppeteer-extra-plugin-stealth (though be aware of terms of service).

Frequently Asked Questions

Why does my Puppeteer script work locally but fail on a server?

Differences in environment: missing system dependencies for Chrome, different network settings, or headless mode being disabled. Use puppeteer.launch({ args: ['--no-sandbox'] }) on Linux servers if you get sandbox errors.

How do I debug a page that loads but my selector never finds an element?

Take a screenshot to see the page state. Then use page.evaluate(() => document.body.innerHTML) to inspect the DOM. The element might be in an iframe or shadow DOM—use page.frames() or pierce shadow roots.

What does 'Error: net::ERR_CONNECTION_REFUSED' mean in Puppeteer?

It means the browser couldn't connect to the target URL. Check the URL is correct, the server is running, and there are no firewall rules blocking the connection.

Can I use Puppeteer's debugger with VS Code?

Yes, create a launch.json with a Node.js configuration, set breakpoints, and run. Puppeteer calls are just promises, so you can step through them.

How do I debug a popup or new tab opened by my script?

Listen for the popup event on the page: page.on('popup', popup => { popup.on('console', ...); }). You can then interact with the popup page object.

Why is my script timing out on page.goto()?

Increase the timeout with page.goto(url, { timeout: 60000 }) or set the default. Also check if the page is stuck on a resource (like a slow script); you can use page.setRequestInterception to abort unnecessary requests.