TestCafe Hammerhead Proxy

31.7.7 · active · verified Sun Apr 19

testcafe-hammerhead is a robust, low-level web proxy library serving as the core engine for the TestCafe end-to-end testing framework. It functions as a URL-rewriting proxy, transparently modifying URLs within proxied web pages and intercepting access to URL-containing properties to provide original values, making it appear to the client that the page is hosted at its original location. The current stable version is 31.7.7, with frequent patch and minor releases to address bugs, security vulnerabilities, and improve compatibility. Key differentiators include its ability to handle HTTP/HTTPS, WebSockets, EventSource, and file uploads, along with extensive request and response modification capabilities. It is primarily used programmatically to establish and configure proxy servers for web traffic manipulation.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create and run a basic Hammerhead URL-rewriting proxy server, listening on a specified port and hostname. It shows how to integrate it with a standard Node.js HTTP server, register event listeners, and handle graceful shutdown.

import { createProxy } from 'testcafe-hammerhead';
import * as http from 'http';

// Configure the Hammerhead proxy instance
const proxy = createProxy({
  port: 8000,
  hostname: 'localhost',
  // Optionally, you can specify an external proxy to chain to
  // externalProxyHost: process.env.EXTERNAL_PROXY_HOST ?? '',
  // externalProxyPort: parseInt(process.env.EXTERNAL_PROXY_PORT ?? '8080', 10),
});

// Create a standard Node.js HTTP server
const server = http.createServer((req, res) => {
  // Pass incoming requests to the Hammerhead proxy's request handler
  proxy.onRequest(req, res);
});

// Listen on the configured port
server.listen(proxy.port, () => {
  console.log(`Hammerhead proxy listening on http://${proxy.hostname}:${proxy.port}`);
  console.log(`Try visiting a URL like: http://${proxy.hostname}:${proxy.port}/http://example.com`);
});

// You can register custom event handlers with the proxy instance
proxy.on('request', (req, res, next) => {
  // console.log(`Proxying request for: ${req.url}`);
  next(); // Must call next() to continue processing the request
});

proxy.on('error', (error) => {
  console.error('Hammerhead proxy error:', error);
});

// Graceful shutdown
process.on('SIGINT', () => {
  console.log('Shutting down Hammerhead proxy...');
  server.close(() => {
    console.log('HTTP server closed.');
    proxy.close(() => {
        console.log('Hammerhead proxy instance closed.');
        process.exit(0);
    });
  });
});

view raw JSON →