HTTP Metrics Middleware

2.2.1 · active · verified Wed Apr 22

http-metrics-middleware is an Express.js middleware designed to integrate Prometheus metrics into Node.js applications, currently stable at version 2.2.1. It provides a convenient wrapper around `prom-client`, offering a set of default HTTP request metrics such as duration histograms and summaries, as well as status code counts. The library maintains a regular release cadence, primarily driven by dependency updates, security patches, and minor enhancements. Key differentiators include its configurable options for metric labels, such as normalized URL paths, and custom time/quantile buckets, allowing fine-grained control over the collected data. While primarily built for Express, it can be seamlessly integrated into Koa applications using `koa-connect`. It focuses on providing a robust, opinionated solution for common HTTP metrics without requiring extensive manual setup of individual `prom-client` metrics.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up `http-metrics-middleware` with Express, configure a custom metrics path, and integrate a custom Prometheus counter using the exposed `promClient` instance.

const express = require('express');
const MetricsMiddleware = require('http-metrics-middleware');
const promClient = require('http-metrics-middleware').promClient;

const app = express();
const port = 3000;

// Initialize the middleware with custom options
const metrics = new MetricsMiddleware({
  metricsPath: '/app-metrics', // Custom path for metrics endpoint
  includePath: true, // Include path label (use with caution for high cardinality)
  timeBuckets: [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 2], // More granular buckets
});

// Use the middleware to expose the metrics endpoint
app.use(metrics.initRoutes());

// Example custom metric using the exposed promClient
const myCustomCounter = new promClient.Counter({
  name: 'my_app_custom_operations_total',
  help: 'Total number of custom operations',
  labelNames: ['operation_type'],
});

// Sample API route to increment custom metric
app.get('/api/data', (req, res) => {
  myCustomCounter.inc({ operation_type: 'read' });
  res.status(200).json({ message: 'Data fetched successfully' });
});

app.post('/api/data', (req, res) => {
    myCustomCounter.inc({ operation_type: 'write' });
    res.status(201).json({ message: 'Data created successfully' });
});

// Root route
app.get('/', (req, res) => {
  res.send('Hello from http-metrics-middleware example!');
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
  console.log(`Prometheus metrics available at http://localhost:${port}/app-metrics`);
});

view raw JSON →