{"id":17442,"library":"http-metrics-middleware","title":"HTTP Metrics Middleware","description":"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.","status":"active","version":"2.2.1","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/qlik-oss/http-metrics-middleware","tags":["javascript","express","koa","prometheus","metrics"],"install":[{"cmd":"npm install http-metrics-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add http-metrics-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add http-metrics-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Primary framework for which the middleware is designed.","package":"express","optional":true},{"reason":"Core Prometheus client library that this middleware wraps and exposes.","package":"prom-client","optional":false},{"reason":"Required for integrating the middleware with Koa applications.","package":"koa-connect","optional":true}],"imports":[{"note":"The library primarily uses CommonJS `require()` syntax as shown in official examples. Direct ESM `import` is not officially supported or documented for the main class.","wrong":"import { MetricsMiddleware } from 'http-metrics-middleware'","symbol":"MetricsMiddleware","correct":"const MetricsMiddleware = require('http-metrics-middleware')"},{"note":"The underlying `prom-client` instance is exposed as a property on the main module for defining custom metrics.","symbol":"promClient","correct":"const promClient = require('http-metrics-middleware').promClient"},{"note":"`initRoutes` is a function that returns the actual middleware. It must be called to be used correctly with `app.use`.","wrong":"app.use(metrics.initRoutes)","symbol":"initRoutes","correct":"app.use(metrics.initRoutes())"}],"quickstart":{"code":"const express = require('express');\nconst MetricsMiddleware = require('http-metrics-middleware');\nconst promClient = require('http-metrics-middleware').promClient;\n\nconst app = express();\nconst port = 3000;\n\n// Initialize the middleware with custom options\nconst metrics = new MetricsMiddleware({\n  metricsPath: '/app-metrics', // Custom path for metrics endpoint\n  includePath: true, // Include path label (use with caution for high cardinality)\n  timeBuckets: [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 2], // More granular buckets\n});\n\n// Use the middleware to expose the metrics endpoint\napp.use(metrics.initRoutes());\n\n// Example custom metric using the exposed promClient\nconst myCustomCounter = new promClient.Counter({\n  name: 'my_app_custom_operations_total',\n  help: 'Total number of custom operations',\n  labelNames: ['operation_type'],\n});\n\n// Sample API route to increment custom metric\napp.get('/api/data', (req, res) => {\n  myCustomCounter.inc({ operation_type: 'read' });\n  res.status(200).json({ message: 'Data fetched successfully' });\n});\n\napp.post('/api/data', (req, res) => {\n    myCustomCounter.inc({ operation_type: 'write' });\n    res.status(201).json({ message: 'Data created successfully' });\n});\n\n// Root route\napp.get('/', (req, res) => {\n  res.send('Hello from http-metrics-middleware example!');\n});\n\napp.listen(port, () => {\n  console.log(`Server listening at http://localhost:${port}`);\n  console.log(`Prometheus metrics available at http://localhost:${port}/app-metrics`);\n});","lang":"javascript","description":"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."},"warnings":[{"fix":"Upgrade your Node.js runtime environment to version 10 or higher to ensure compatibility.","message":"Version 1.2.0 and subsequent versions of `http-metrics-middleware` require Node.js v10 or above. Older Node.js environments will not be supported.","severity":"breaking","affected_versions":">=1.2.0"},{"fix":"Set `includePath: false` in the middleware options or ensure your `normalizePath` function or Express route definitions heavily restrict path parameters to a limited set of known values.","message":"Enabling the `includePath` option can lead to high cardinality in your Prometheus metrics if your application has dynamic URL paths with many unique values. This can drastically increase memory usage and storage requirements for Prometheus.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Carefully review the changelogs of `express` and `prom-client` when upgrading `http-metrics-middleware` to newer versions to anticipate any breaking changes in their APIs or behaviors.","message":"Updates to underlying dependencies like `express` (v4.21.2 in v2.2.0, v4.19.2 in v2.1.4) and `prom-client` (v13.1.0 in v2.1.2, latest in v2.1.5) may introduce breaking changes from those libraries. Review their respective changelogs.","severity":"breaking","affected_versions":">=2.1.2"},{"fix":"No direct user action is typically required for production code, but be aware if your CI/CD or local development environment relied on `@after-work.js/aw`.","message":"In version 2.1.5, the archived dev-dependency `@after-work.js/aw` was removed and replaced by `mocha` as part of a CVE fix. While primarily a dev dependency, be aware of changes in the test runner if you integrate with internal testing utilities.","severity":"breaking","affected_versions":">=2.1.5"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Use the CommonJS `require` syntax: `const MetricsMiddleware = require('http-metrics-middleware')`.","cause":"Attempting to import the `MetricsMiddleware` class using ESM `import` syntax (`import { MetricsMiddleware } from 'http-metrics-middleware'`) in a CommonJS module.","error":"ReferenceError: MetricsMiddleware is not defined"},{"fix":"Ensure you have called `app.use(metrics.initRoutes())` after creating an instance of `MetricsMiddleware`.","cause":"The middleware responsible for exposing the Prometheus metrics endpoint was not properly initialized or added to the Express application.","error":"GET /metrics 404 Not Found"},{"fix":"Either disable the conflicting default metric via `http-metrics-middleware` options (e.g., `enableDurationHistogram: false`) or choose a unique name for your custom metric.","cause":"Attempting to create a custom `prom-client` metric with a name that conflicts with one of the default metrics provided by `http-metrics-middleware`.","error":"Error: A metric with the name http_request_duration_seconds has already been registered."},{"fix":"Ensure requests are hitting your application. Place `app.use(metrics.initRoutes())` early in your middleware chain, preferably before any routes that you want to measure. Custom metrics will only appear if their `inc()` or `observe()` methods are called.","cause":"The middleware is active but no HTTP requests are being made to your Express application, or the middleware is placed too late in the Express middleware chain to capture requests.","error":"Prometheus scrape endpoint returns an empty response or only default Node.js metrics."}],"ecosystem":"npm","meta_description":null}