October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

How to Intercept HTTP Requests with Puppeteer

Use Puppeteer’s request interception to forward, block, or mock browser traffic—and learn how to avoid stalled requests and duplicate resolutions.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To intercept browser requests in Puppeteer, call await page.setRequestInterception(true) before navigation, then handle the page’s request event. Resolve each request with request.continue(), request.abort(), or request.respond(). If you leave a request unresolved, it stalls.

Enable interception and handle every request

This runnable example blocks PNG and JPEG requests and lets other requests proceed. The URL suffix check is illustrative: production filters should match the URLs or request properties that matter to your task.

As an Amazon Associate I earn from qualifying purchases.

import puppeteer from 'puppeteer';

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

  await page.setRequestInterception(true);
  page.on('request', request => {
    if (request.isInterceptResolutionHandled()) return;

    if (request.url().endsWith('.png') || request.url().endsWith('.jpg')) {
      request.abort();
    } else {
      request.continue();
    }
  });

  await page.goto('https://example.com');
} finally {
  await browser.close();
}

Enable interception before the navigation or other activity that creates requests you want to handle. Puppeteer’s guide warns: “Once request interception is enabled, every request will stall unless it’s continued, responded or aborted; or completed using the browser cache.”

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose how each request should be resolved

Continue the request

Call request.continue() to send the request onward. Its optional overrides can change supported request properties, such as headers. Check the current continue API reference for the supported override shape. With a single handler, no priority is needed.

Abort the request

Call request.abort() to cancel a request. Use a condition based on the actual URL, resource type, or other relevant request data rather than relying on a filename suffix if the target could use query strings or different URL patterns.

Return a mock response

Call request.respond() to fulfill a request with a response you provide. This is useful for deterministic tests that should not contact the real endpoint. Interception must be enabled first. See Puppeteer’s request-interception API for current details.

Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

Mock an endpoint with a controlled response

This example returns JSON for requests whose URL contains the chosen endpoint path and continues all other traffic. Adapt the match to the precise endpoint you intend to intercept.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import puppeteer from 'puppeteer';

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

  await page.setRequestInterception(true);
  page.on('request', request => {
    if (request.isInterceptResolutionHandled()) return;

    if (request.url().includes('/api/example')) {
      request.respond({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify({ ok: true, source: 'mock' })
      });
    } else {
      request.continue();
    }
  });

  await page.goto('https://example.com');
} finally {
  await browser.close();
}

Prevent duplicate-resolution errors

A request may be handled by another listener, including one installed by a third-party package. Check request.isInterceptResolutionHandled() before resolving it. If the handler awaits any asynchronous work, check again afterwards and resolve immediately after that fresh check: another handler may have acted while yours was paused.

page.on('request', async request => {
  if (request.isInterceptResolutionHandled()) return;

  const shouldBlock = await policyCheck(request.url());

  // Re-check after awaiting: another handler may have resolved it meanwhile.
  if (request.isInterceptResolutionHandled()) return;

  if (shouldBlock) {
    request.abort();
  } else {
    request.continue();
  }
});

Keep the final check and the resolving call together synchronously. A check made only before an await does not protect the later call.

Coordinate multiple handlers with priorities

When multiple listeners need to propose outcomes, Puppeteer’s Cooperative Intercept Mode lets them supply numeric priorities to abort(), continue(), or respond(). The highest priority wins; when priorities tie, abort outranks respond, and respond outranks continue.

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

Cooperative arbitration requires every resolution to include a numeric priority. If even one handler resolves without one, legacy immediate resolution applies, so the other handlers may not participate in arbitration as expected. Continue to check whether the request is already handled, particularly when third-party listeners may use legacy behavior. For ordinary single-handler cases, the guide recommends using the default priority, zero, when a priority is needed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Tell transport failures from HTTP error responses

Puppeteer emits request, response, requestfinished, and requestfailed events. A server response with status 404 or 503 is still an HTTP response; it is not a requestfailed event just because the status indicates an error. Use response status checks for HTTP errors and requestfailed to diagnose requests that failed at the browser/network level. See the Page events reference.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common interception problems

  • Navigation hangs: interception may be enabled but some request path does not call continue(), abort(), or respond(). Ensure every branch resolves the request.
  • “Request is already handled” or duplicate-resolution behavior: another handler may have resolved it. Check isInterceptResolutionHandled(), including again after every asynchronous wait.
  • Images still load: the filter may not match their actual URLs. Inspect request.url() and consider the resource type or a more accurate URL condition instead of a bare suffix check.
  • Mock does not apply: confirm interception is enabled before the request occurs and that the match targets the request URL you expect. Ensure the matching branch calls respond() and all other branches still resolve.
  • HTTP 404 counted as a request failure: inspect the response status; an HTTP error response is distinct from Puppeteer’s requestfailed event.
  • Priorities seem ignored: cooperative arbitration only works if all handlers use numeric priorities. A single legacy resolution without priority resolves immediately.

Or skip the browser setup

If your goal is to capture a website rather than control its requests in a browser script, ScreenshotNeo returns a screenshot or PDF from one GET request. Its cURL example is:

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

See the ScreenshotNeo API documentation for request options. ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before capture; 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. Sign up for ScreenshotNeo free.

Frequently Asked Questions

Does enabling interception affect requests made before it was enabled?

No. Enable it before the navigation or other activity that triggers the requests you need to handle.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Does a 404 trigger Puppeteer’s requestfailed event?

No. A 404 is an HTTP response; requestfailed indicates a browser/network-level request failure.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.