Inspect Active Connections in Axios

Axios does not provide a single built-in property to view active connections directly. However, you can inspect, monitor, and track in-flight requests and open sockets using underlying HTTP agents in Node.js, Axios interceptors, or browser developer tools. This article outlines the primary methods available to inspect active connections managed by the Axios HTTP client.

1. Inspecting the Node.js http.Agent

In a Node.js environment, Axios relies on the native http and https modules to manage connections through an Agent. By attaching a custom agent, you can inspect its internal socket pools:

const axios = require('axios');
const http = require('http');

const httpAgent = new http.Agent({ keepAlive: true });
const client = axios.create({ httpAgent });

// Inspect the active sockets
function getActiveSocketCount(agent) {
  return Object.values(agent.sockets).reduce((acc, sockets) => acc + sockets.length, 0);
}

console.log('Active Sockets:', getActiveSocketCount(httpAgent));
console.log('Active Socket Details:', httpAgent.sockets);

2. Tracking Active Requests via Axios Interceptors

A universal method that works in both Node.js and browser environments is tracking active requests using Axios request and response interceptors. This approach maintains a count or registry of in-flight requests.

const axios = require('axios');

const client = axios.create();
const activeRequests = new Map();

client.interceptors.request.use((config) => {
  const requestId = Symbol('requestId');
  config.metadata = { requestId };
  activeRequests.set(requestId, {
    url: config.url,
    method: config.method,
    startTime: Date.now(),
  });
  return config;
});

client.interceptors.response.use(
  (response) => {
    activeRequests.delete(response.config.metadata?.requestId);
    return response;
  },
  (error) => {
    if (error.config?.metadata?.requestId) {
      activeRequests.delete(error.config.metadata.requestId);
    }
    return Promise.reject(error);
  }
);

// Inspect active connections anytime
console.log('Active requests count:', activeRequests.size);
console.log('Active requests details:', Array.from(activeRequests.values()));

3. Using Debugging Libraries

You can use community packages such as axios-debug-log to automatically log request lifecycles. This method outputs connection events (request sent, response received, error thrown) to the console or log streams using the standard debug library, allowing you to follow connection creation and teardown in real time.

4. Browser Network Inspection

When running Axios in a browser: