{"id":17883,"library":"prometheus-middleware","title":"Prometheus Middleware for Node.js HTTP Servers","description":"The `prometheus-middleware` package provides a straightforward solution for integrating Prometheus metrics into Node.js HTTP applications. Currently at version 1.4.2, it appears to maintain an active development cadence given its continuous integration setup and recent releases. It acts as an abstraction layer, setting up an HTTP server to expose metrics, instantiating and exposing a `prom-client` instance, and patching the native Node.js HTTP server to automatically track request-response times. A key differentiator is its out-of-the-box support for popular Node.js HTTP frameworks like Express and Fastify, along with the default Node.js HTTP server. It also includes sensible defaults, such as normalizing 404 error paths to prevent high cardinality issues in Prometheus, and automatically collects metrics for event loop, garbage collection, CPU, and memory usage. Developers can also easily define custom metrics using the underlying `prom-client` instance.","status":"active","version":"1.4.2","language":"javascript","source_language":"en","source_url":"https://github.com/VoodooTeam/prometheus-middleware","tags":["javascript","apm","prometheus","middleware","latency","handles","eventloop","gc","cpu","typescript"],"install":[{"cmd":"npm install prometheus-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add prometheus-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add prometheus-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core metrics collection library used internally and exposed for custom metric definitions.","package":"prom-client","optional":false}],"imports":[{"note":"The default export is the APM class constructor. Named export also available for clarity.","wrong":"import { APM } from 'prometheus-middleware'.APM;","symbol":"APM","correct":"import APM from 'prometheus-middleware';\n// Or for the class itself:\nimport { APM } from 'prometheus-middleware';"},{"note":"This is the primary way shown in the documentation examples for Node.js environments.","symbol":"APM (CommonJS)","correct":"const APM = require('prometheus-middleware');"},{"note":"Access `prom-client` metric constructors via the `apm.client` instance after initialization.","symbol":"APM.client.Counter","correct":"import APM from 'prometheus-middleware';\nconst apm = new APM();\nconst counter = new apm.client.Counter({\n  name: 'my_counter',\n  help: 'A custom counter metric'\n});"}],"quickstart":{"code":"import APM from 'prometheus-middleware';\nimport http from 'http';\n\nconst apm = new APM({\n  PORT: 9350,\n  METRICS_ROUTE: '/metrics'\n});\napm.init();\n\n// Example of adding a custom metric\nconst customRequestsCounter = new apm.client.Counter({\n  name: 'custom_http_requests_total',\n  help: 'Total number of custom HTTP requests',\n  labelNames: ['method', 'route', 'code']\n});\n\n// Create a simple HTTP server to demonstrate the middleware\nconst server = http.createServer((req, res) => {\n  if (req.url === '/test') {\n    customRequestsCounter.inc({ method: req.method, route: '/test', code: 200 });\n    res.writeHead(200, { 'Content-Type': 'text/plain' });\n    res.end('Hello from /test\\n');\n  } else {\n    res.writeHead(404, { 'Content-Type': 'text/plain' });\n    res.end('Not Found\\n');\n  }\n});\n\nserver.listen(3000, () => {\n  console.log('HTTP server listening on port 3000');\n  console.log('Prometheus metrics available at http://localhost:9350/metrics');\n});\n\n// Graceful shutdown to destroy the APM instance and its HTTP server\nprocess.on('SIGTERM', () => {\n  console.log('SIGTERM received, destroying APM...');\n  apm.destroy();\n  server.close(() => {\n    console.log('HTTP server closed.');\n    process.exit(0);\n  });\n});","lang":"typescript","description":"This quickstart initializes `prometheus-middleware` to expose metrics on port 9350 at `/metrics`. It also demonstrates adding a custom Prometheus counter using `apm.client.Counter` and integrates it into a basic Node.js HTTP server. A graceful shutdown mechanism is included."},"warnings":[{"fix":"If unique 404 path labels are required, initialize APM with `new APM({ NORMALIZE_ENDPOINT: false })`. Be aware of potential high cardinality with this setting.","message":"By default, the middleware normalizes the 'path' label for HTTP 404 responses to avoid high cardinality issues in Prometheus. If your monitoring strategy requires unique path labels for all 404s, you must explicitly set `NORMALIZE_ENDPOINT: false` in the configuration.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure your Node.js environment is updated to version 16.0.0 or later. The package officially tests and supports Node.js 18.x, 20.x, and 22.x.","message":"The package requires Node.js version 16.0.0 or higher. Running on older Node.js versions will result in startup failures.","severity":"breaking","affected_versions":"<1.0.0"},{"fix":"For production deployments, use Node.js versions 18.x, 20.x, or 22.x to benefit from tested compatibility. If using 16.x, ensure thorough application-level testing.","message":"While the documentation states `16.x` is supported, the compatibility table explicitly marks it as 'not tested'. Prioritize Node.js 18.x, 20.x, or 22.x for environments where thorough testing has been performed by the library authors.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"If your project is an ESM module (e.g., `\"type\": \"module\"` in package.json), use `import APM from 'prometheus-middleware';`. If it's CommonJS, use `const APM = require('prometheus-middleware');`.","cause":"Attempting to use `require()` syntax in an ES Module context, or trying to `import` in a CommonJS context without proper configuration.","error":"Error [ERR_REQUIRE_ESM]: require() of ES Module ...prometheus-middleware.js not supported."},{"fix":"For CommonJS, use `const APM = require('prometheus-middleware');`. For ESM, use `import APM from 'prometheus-middleware';` or `import { APM } from 'prometheus-middleware';`.","cause":"Incorrectly importing the `APM` class, such as using named import syntax for a default export in CommonJS, or incorrect path.","error":"TypeError: APM is not a constructor"},{"fix":"Review your `prometheus-middleware` configuration. The default behavior normalizes 404 paths. If this is not sufficient, consider implementing custom path normalization using a library like `express-url-trimmer` before `prometheus-middleware` in your HTTP server's middleware chain, or ensure `NORMALIZE_ENDPOINT` is not set to `false` without careful consideration.","cause":"Prometheus alert indicating too many unique values for the `path` label on HTTP metrics, often due to dynamic URL segments not being normalized.","error":"metrics_path_label_cardinality_high"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}