Enhanced HTTP/HTTPS agents with keepalive functionality for Node.js applications
npx @tessl/cli install tessl/npm-agentkeepalive@4.6.0Agent Keep Alive provides enhanced HTTP and HTTPS agents with keepalive functionality for Node.js applications. It extends the native Node.js http.Agent with features like automatic keepalive enablement, socket timeout management, TTL for active sockets, and Nagle's algorithm disabling to improve performance and prevent socket leaks.
npm install agentkeepalive// Default export is HttpAgent class
const Agent = require('agentkeepalive');
// Named exports
const { HttpAgent, HttpsAgent, constants } = require('agentkeepalive');For ES modules:
// Default export is HttpAgent class
import Agent from 'agentkeepalive';
// Named exports
import { HttpAgent, HttpsAgent, constants } from 'agentkeepalive';TypeScript:
// Default export is HttpAgent class
import Agent, { HttpAgent, HttpsAgent, constants } from 'agentkeepalive';
import type { AgentStatus, HttpOptions, HttpsOptions } from 'agentkeepalive';const Agent = require('agentkeepalive');
// Create HTTP agent with default settings
const agent = new Agent({
keepAlive: true,
freeSocketTimeout: 4000,
timeout: 8000,
socketActiveTTL: null
});
// Use with http.request
const http = require('http');
const options = {
hostname: 'example.com',
port: 80,
path: '/',
method: 'GET',
agent: agent
};
const req = http.request(options, (res) => {
console.log('reused socket:', req.reusedSocket);
res.on('data', (chunk) => {
console.log(chunk.toString());
});
});
req.end();
// Check agent status
console.log(agent.getCurrentStatus());Agent Keep Alive is built around several key components:
http.Agent with keepalive featuresThe package exports structure from index.js:
// Default export is HttpAgent class
module.exports = HttpAgent;
// Named exports
module.exports.HttpAgent = HttpAgent;
module.exports.HttpsAgent = HttpsAgent;
module.exports.constants = constants;Enhanced HTTP agent with keepalive functionality and socket management.
/**
* Enhanced HTTP agent with keepalive functionality
* @param {HttpOptions} options - Configuration options
*/
class HttpAgent extends http.Agent {
constructor(options?: HttpOptions);
/** Check if agent status has changed since last check */
readonly statusChanged: boolean;
/** Calculate timeout for socket based on TTL and freeSocketTimeout
* @returns {number} timeout in ms if should update, <= 0 if should destroy, undefined if no custom timeout */
calcSocketTimeout(socket: Socket): number | undefined;
/** Determine if socket should be kept alive and set appropriate timeout */
keepSocketAlive(socket: Socket): boolean;
/** Handle socket reuse, mark request as reused and update counters */
reuseSocket(...args: any[]): void;
/** Create new connection with proper initialization */
createConnection(options: NetConnectOpts, cb?: Function): Socket;
/** Create socket for request (inherited from http.Agent) */
createSocket(req: IncomingMessage, options: RequestOptions, cb: Function): void;
/** Get current agent and socket status information */
getCurrentStatus(): AgentStatus;
// Deprecated getters (use options instead) - these log deprecation warnings
get freeSocketKeepAliveTimeout(): number;
get timeout(): number;
get socketActiveTTL(): number;
}
interface HttpOptions extends http.AgentOptions {
/** Enable keepalive (default: true) */
keepAlive?: boolean;
/** Timeout for free sockets in milliseconds (default: 4000) */
freeSocketTimeout?: number;
/** Deprecated: use freeSocketTimeout instead */
freeSocketKeepAliveTimeout?: number;
/** Timeout for active sockets in milliseconds */
timeout?: number;
/** Time-to-live for active sockets in milliseconds */
socketActiveTTL?: number;
}HTTPS agent extending HttpAgent with SSL/TLS support.
/**
* HTTPS agent extending HttpAgent with SSL/TLS support
* @param {HttpsOptions} options - Configuration options
*/
class HttpsAgent extends HttpAgent {
constructor(options?: HttpsOptions);
/** Create HTTPS connection with SSL/TLS support */
createConnection(options: NetConnectOpts, cb?: Function): Socket;
/** Create socket for HTTPS request (inherited from http.Agent) */
createSocket(req: IncomingMessage, options: RequestOptions, cb: Function): void;
// Inherited from Node.js https.Agent
getName(options: RequestOptions): string;
_getSession(sessionId: string): any;
_cacheSession(sessionId: string, session: any): void;
_evictSession(sessionId: string): void;
}
interface HttpsOptions extends https.AgentOptions {
/** Enable keepalive (default: true) */
keepAlive?: boolean;
/** Timeout for free sockets in milliseconds (default: 4000) */
freeSocketTimeout?: number;
/** Deprecated: use freeSocketTimeout instead */
freeSocketKeepAliveTimeout?: number;
/** Timeout for active sockets in milliseconds */
timeout?: number;
/** Time-to-live for active sockets in milliseconds */
socketActiveTTL?: number;
}Real-time monitoring of agent and socket statistics.
interface AgentStatus {
/** Total number of sockets created */
createSocketCount: number;
/** Number of socket creation errors */
createSocketErrorCount: number;
/** Number of sockets closed */
closeSocketCount: number;
/** Number of socket errors */
errorSocketCount: number;
/** Number of socket timeouts */
timeoutSocketCount: number;
/** Total number of requests processed */
requestCount: number;
/** Current free sockets by hostname */
freeSockets: { [key: string]: number };
/** Current active sockets by hostname */
sockets: { [key: string]: number };
/** Current pending requests by hostname */
requests: { [key: string]: number };
}Automatic enhancement of HTTP requests with socket reuse information.
// Properties added to http.IncomingMessage
interface IncomingMessage {
/** Indicates if the request is using a reused socket */
reusedSocket?: boolean;
}Internal symbols used by the agents for socket management.
interface Constants {
/** Symbol for tracking current ID counter */
CURRENT_ID: Symbol;
/** Symbol for create ID method */
CREATE_ID: Symbol;
/** Symbol for socket initialization method */
INIT_SOCKET: Symbol;
/** Symbol for HTTPS connection creation method */
CREATE_HTTPS_CONNECTION: Symbol;
/** Symbol for tracking socket creation timestamp */
SOCKET_CREATED_TIME: Symbol;
/** Symbol for socket name/identifier */
SOCKET_NAME: Symbol;
/** Symbol for tracking total request count on socket */
SOCKET_REQUEST_COUNT: Symbol;
/** Symbol for tracking finished request count on socket */
SOCKET_REQUEST_FINISHED_COUNT: Symbol;
}
const constants: Constants;For browser environments, the package provides noop implementations since native browser APIs don't use agents.
// In browser.js - noop implementations for browser compatibility
function noop(): void;
// CommonJS exports
module.exports = noop;
module.exports.HttpsAgent = noop;freeSocketTimeout insteadfreeSocketTimeout * 2 or 8000ms minimum)http.AgentOptions and https.AgentOptionsThe agents provide enhanced error handling with custom error types and automatic error recovery:
// Socket timeout errors
const error = new Error('Socket timeout');
error.code = 'ERR_SOCKET_TIMEOUT';
error.timeout = timeoutValue; // timeout value in milliseconds
// Handle connection reuse errors
const req = http.request(options, (res) => {
// handle response
}).on('error', (err) => {
if (req.reusedSocket && err.code === 'ECONNRESET') {
// This is a keep-alive race condition - safe to retry
console.log('Connection reset on reused socket - consider retry');
}
});The package logs deprecation warnings for legacy options:
options.keepAliveTimeout → use options.freeSocketTimeoutoptions.freeSocketKeepAliveTimeout → use options.freeSocketTimeoutagent.freeSocketKeepAliveTimeout → use agent.options.freeSocketTimeoutagent.timeout → use agent.options.timeoutagent.socketActiveTTL → use agent.options.socketActiveTTLsocket.setNoDelay(true) for improved performancereq.reusedSocket property indicates connection reuseECONNRESET errorsconst { HttpsAgent } = require('agentkeepalive');
const httpsAgent = new HttpsAgent({
keepAlive: true,
freeSocketTimeout: 5000,
timeout: 10000,
socketActiveTTL: 60000,
maxSockets: 50,
maxFreeSockets: 10,
// Standard https.AgentOptions
rejectUnauthorized: true,
ca: certificateAuthority
});
const https = require('https');
https.globalAgent = httpsAgent;const agent = new Agent();
// Check if status has changed
if (agent.statusChanged) {
const status = agent.getCurrentStatus();
console.log('Agent Status:', {
activeSockets: status.sockets,
freeSockets: status.freeSockets,
requests: status.requests,
totalRequests: status.requestCount,
errors: status.errorSocketCount
});
}const agent = new Agent({
freeSocketTimeout: 3000, // 3 seconds for idle sockets
socketActiveTTL: 30000, // 30 seconds max lifetime
timeout: 10000 // 10 seconds for active requests
});
// Agent automatically handles:
// - Socket creation and initialization
// - Timeout management for idle and active sockets
// - Cleanup of expired sockets
// - Error handling and socket destruction