Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Puppeteer Puppeteer Cdp HTTPRequest

From Leeroopedia
Property Value
sources packages/puppeteer-core/src/cdp/HTTPRequest.ts
domains HTTP, Network, Request Interception, CDP
last_updated 2026-02-12 00:00 GMT

Overview

Description

The CdpHTTPRequest class is the CDP-specific implementation of the abstract HTTPRequest base class. It represents an individual HTTP request made by the browser and provides both read access to request properties and request interception capabilities.

Key responsibilities include:

  • Request data access -- Exposing request properties including URL (with fragment), HTTP method, headers (lowercased keys), post data, resource type, frame association, initiator info, and navigation status.
  • Post data handling -- Reconstructing post data from postDataEntries (merging binary entries via mergeUint8Arrays) or falling back to the string postData field. Also supports lazy fetching of post data via Network.getRequestPostData for large payloads.
  • Redirect chain tracking -- Maintaining a chain of previous requests that led to this request through HTTP redirects.
  • Request interception -- When interception is enabled, supporting three interception actions:
    • _continue() -- Continues the request with optional overrides (URL, method, post data, headers) via Fetch.continueRequest.
    • _respond() -- Fulfills the request with a custom response (status, headers, body) via Fetch.fulfillRequest.
    • _abort() -- Aborts the request with a specified error reason via Fetch.failRequest.
  • Header management -- Storing headers with lowercased keys and returning cloned copies to prevent external mutation.
  • Failure tracking -- Reporting request failure information via the failure() method.

Data URLs and requests from memory cache cannot be intercepted.

Usage

CdpHTTPRequest instances are created internally by the NetworkManager and emitted via PageEvent.Request, PageEvent.RequestFailed, and PageEvent.RequestFinished events.

Code Reference

Source Location: packages/puppeteer-core/src/cdp/HTTPRequest.ts (301 lines)

Signature:

export class CdpHTTPRequest extends HTTPRequest {
  override id: string;

  constructor(
    client: CDPSession,
    frame: Frame | null,
    interceptionId: string | undefined,
    allowInterception: boolean,
    data: {
      requestId: Protocol.Network.RequestId;
      loaderId?: Protocol.Network.LoaderId;
      documentURL?: string;
      request: Protocol.Network.Request;
      initiator?: Protocol.Network.Initiator;
      type?: Protocol.Network.ResourceType;
    },
    redirectChain: CdpHTTPRequest[],
  );

  override url(): string;
  override resourceType(): ResourceType;
  override method(): string;
  override postData(): string | undefined;
  override hasPostData(): boolean;
  override async fetchPostData(): Promise<string | undefined>;
  override headers(): Record<string, string>;
  override response(): CdpHTTPResponse | null;
  override frame(): Frame | null;
  override isNavigationRequest(): boolean;
  override initiator(): Protocol.Network.Initiator | undefined;
  override redirectChain(): CdpHTTPRequest[];
  override failure(): { errorText: string } | null;
}

Import:

import { CdpHTTPRequest } from 'puppeteer-core/lib/cdp/HTTPRequest.js';

I/O Contract

Inputs:

Parameter Type Required Description
client CDPSession Yes The CDP session for sending interception commands
frame null Yes The frame that initiated this request
interceptionId undefined No The Fetch domain interception ID (required for interception)
allowInterception boolean Yes Whether request interception is enabled
data object Yes CDP network request data including requestId, request details, initiator, and resource type
redirectChain CdpHTTPRequest[] Yes Previous requests in the redirect chain

Outputs:

Output Type Description
url() string The full request URL including any URL fragment
method() string The HTTP method (GET, POST, etc.)
headers() Record<string, string> A cloned copy of the request headers (lowercased keys)
postData() undefined The request post data, if any
response() null The response for this request, or null if not yet received
redirectChain() CdpHTTPRequest[] The chain of redirects leading to this request
failure() null Failure information if the request failed

Usage Examples

// Listen for all requests
page.on('request', request => {
  console.log(request.url(), request.method(), request.resourceType());
});

// Enable request interception
await page.setRequestInterception(true);

// Abort image requests
page.on('request', request => {
  if (request.resourceType() === 'image') {
    request.abort();
  } else {
    request.continue();
  }
});

// Modify request headers
page.on('request', request => {
  request.continue({
    headers: {
      ...request.headers(),
      'X-Custom-Header': 'my-value',
    },
  });
});

// Mock a response
page.on('request', request => {
  if (request.url().endsWith('/api/data')) {
    request.respond({
      status: 200,
      contentType: 'application/json',
      body: JSON.stringify({ key: 'value' }),
    });
  } else {
    request.continue();
  }
});

// Check for request failures
page.on('requestfailed', request => {
  console.log(request.url(), request.failure().errorText);
});

// Inspect redirect chains
page.on('response', response => {
  const chain = response.request().redirectChain();
  if (chain.length > 0) {
    console.log('Redirected from:', chain[0].url());
  }
});

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment