HTTP/HTTPS Proxy Agent for Node.js

1.2.0 · active · verified Wed Apr 22

hpagent is a Node.js library providing HttpProxyAgent and HttpsProxyAgent classes designed to facilitate HTTP and HTTPS requests through proxy servers while leveraging connection keep-alive mechanisms. Currently at version 1.2.0, it maintains an active development status with periodic releases introducing features and bug fixes, such as strict TypeScript support and improved proxy handling. A key differentiator is its ability to serve as a drop-in replacement for Node.js's native `http` and `https` agents, offering robust proxy configuration options, including basic authentication via URL or custom headers, and the ability to pass specific options for the proxy CONNECT request. The library explicitly demonstrates compatibility with popular userland HTTP clients like `got`, `needle`, `node-fetch`, and `simple-get`, and ships with TypeScript type definitions, making it suitable for modern Node.js applications (Node.js >=14 is required since v1.0.0).

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to create and use an HttpProxyAgent with basic authentication for an HTTP request via Node.js's built-in http module. This code uses environment variables for sensitive data and target host/port, making it runnable and adaptable.

import http from 'node:http';
import { HttpProxyAgent } from 'hpagent';

const PROXY_USER = process.env.PROXY_USERNAME ?? 'user';
const PROXY_PASS = process.env.PROXY_PASSWORD ?? 'pwd';
const PROXY_HOST = process.env.PROXY_HOST ?? 'localhost';
const PROXY_PORT = process.env.PROXY_PORT ?? '8080';
const TARGET_HOST = process.env.TARGET_HOST ?? 'localhost';
const TARGET_PORT = process.env.TARGET_PORT ?? '9200';

const agent = new HttpProxyAgent({
  keepAlive: true,
  keepAliveMsecs: 1000,
  maxSockets: 256,
  maxFreeSockets: 256,
  proxy: `http://${PROXY_USER}:${PROXY_PASS}@${PROXY_HOST}:${PROXY_PORT}`
});

http.get(`http://${TARGET_HOST}:${TARGET_PORT}`, { agent })
    .on('response', (res) => {
        console.log(`STATUS: ${res.statusCode}`);
        console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
        res.setEncoding('utf8');
        res.on('data', (chunk) => {
            console.log(`BODY: ${chunk}`);
        });
        res.on('end', () => {
            console.log('No more data in response.');
        });
    })
    .on('error', (e) => {
        console.error(`problem with request: ${e.message}`);
    })
    .end();

view raw JSON →