HTTP Keep-Alive Agent

0.6.1 · abandoned · verified Wed Apr 22

forever-agent is a Node.js module that provides an HTTP Agent designed to maintain persistent socket connections between `http.request` calls, enabling HTTP keep-alive behavior. It was originally an internal component of the widely popular, but now deprecated, `request` HTTP client library. The current stable version, 0.6.1, was last published over 11 years ago in April 2015. With the official deprecation of its progenitor `request` library in 2020, forever-agent itself is considered unmaintained and has seen no significant updates for over a decade. Its key differentiator was offering direct control over connection pooling for keep-alive outside of the `request` library, at a time when native Node.js HTTP client features were less developed regarding persistent connections.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate `ForeverAgent` and use it with Node.js's native `http.request` to achieve persistent (keep-alive) connections across multiple requests to the same host.

const http = require('http');
const ForeverAgent = require('forever-agent');

const agent = new ForeverAgent();

// Define request options, ensuring 'Connection: keep-alive' is set.
const options = {
  hostname: 'httpbin.org', // A public service for testing HTTP requests
  port: 80,
  path: '/get',
  method: 'GET',
  agent: agent, // Crucially, assign the forever-agent instance
  headers: {
    'Connection': 'keep-alive'
  }
};

function makeKeepAliveRequest(id) {
  return new Promise((resolve, reject) => {
    console.log(`[Request ${id}] Sending request...`);
    const req = http.request(options, (res) => {
      let data = '';
      res.on('data', (chunk) => { data += chunk; });
      res.on('end', () => {
        console.log(`[Request ${id}] Status: ${res.statusCode}, Socket Local Port: ${req.socket ? req.socket.localPort : 'N/A'}`);
        resolve(res.statusCode);
      });
    });

    req.on('error', (e) => {
      console.error(`[Request ${id}] Problem with request: ${e.message}`);
      reject(e);
    });

    req.end();
  });
}

async function demonstrateKeepAlive() {
  console.log('Demonstrating HTTP keep-alive with forever-agent...');
  await makeKeepAliveRequest(1);
  await makeKeepAliveRequest(2);
  await makeKeepAliveRequest(3);
  console.log('Multiple requests sent. Check console for repeated socket local ports to confirm keep-alive.');
}

demonstrateKeepAlive();

view raw JSON →