Registry / observability / prometheus-api-metrics

prometheus-api-metrics

JSON →
library4.0.0jsnpmunverified

This library provides comprehensive API and process monitoring for Node.js microservices, integrating with Prometheus through `prom-client`. It automatically collects metrics such as response time, request/response size, and server connection counts for each API call, in addition to standard process metrics recommended by Prometheus. It supports both Express and Koa frameworks and allows for custom metrics and exclusion of specific routes. The current stable version is 4.0.0. Releases are somewhat irregular, with significant updates typically every 1-2 years for major/minor versions. Key differentiators include its ease of integration as middleware, support for custom metrics, and the ability to collect HTTP request durations from common HTTP clients. Users must install `prom-client` as a peer dependency.

npm install prometheus-api-metrics
INSTALL
IMPORT
SIG · PROMETHEUS-API-MET
P
prometheus-api-metrics
observabilityjavascriptv4.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

apiMetrics
import apiMetrics from 'prometheus-api-metrics';
import { apiMetrics } from 'prometheus-api-metrics';
The primary middleware function is a default export. For Node.js versions supporting ESM, this is the recommended import.
apiMetrics
const apiMetrics = require('prometheus-api-metrics');
import apiMetrics from 'prometheus-api-metrics';
CommonJS usage for Node.js environments that do not support ESM or for legacy applications.
Options
import type { Options } from 'prometheus-api-metrics';
Type definition for configuring the API metrics middleware.

This quickstart sets up an Express server with the `prometheus-api-metrics` middleware, exposing API and process metrics at the `/metrics` endpoint for Prometheus scraping. It includes custom buckets, a metric prefix, and an excluded route.

import express from 'express'; import apiMetrics from 'prometheus-api-metrics'; import { collectDefaultMetrics, register } from 'prom-client'; const app = express(); const port = 3000; // Start collecting default metrics like CPU, memory, etc. // Interval must be a number, use Number() just in case for env vars collectDefaultMetrics({ prefix: 'my_app_', timeout: Number(process.env.DEFAULT_METRICS_INTERVAL || 10000) }); // Use the API metrics middleware app.use(apiMetrics({ metricsPath: '/metrics', durationBuckets: [0.001, 0.005, 0.015, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 1, 2, 5], metricsPrefix: 'my_service_', excludeRoutes: ['/health'] })); // Define a health check endpoint app.get('/health', (req, res) => { res.status(200).send('OK'); }); // Define a sample API endpoint app.get('/data', (req, res) => { setTimeout(() => { res.json({ message: 'Hello, Prometheus!' }); }, Math.random() * 500); }); // Expose the metrics endpoint for Prometheus to scrape app.get('/metrics', async (req, res) => { try { res.set('Content-Type', register.contentType); res.end(await register.metrics()); } catch (ex) { res.status(500).end(ex); } }); app.listen(port, () => { console.log(`Server listening on http://localhost:${port}`); console.log(`Metrics available at http://localhost:${port}/metrics`); });
Debug
Known issues
breakingNode.js versions older than 18 are no longer supported. Version 4.0.0 removed format support for these older environments.
fix
Upgrade your Node.js environment to version 18 or higher to ensure compatibility.
affects: >=4.0.0
gotchaThe library relies on `prom-client` as a peer dependency. You must install `prom-client` separately in your project, ensuring its version is compatible with the range specified (e.g., `>=12 <=16`).
fix
Install the peer dependency: `npm install prom-client@'^15.0.0'` (adjust the version based on the latest compatible range, currently up to 16.x).
affects: >=1.0.0
gotchaWhen integrating with sub-applications or custom error handlers, ensure the `prometheus-api-metrics` middleware is placed correctly in the middleware chain to accurately capture metrics for all intended routes.
fix
Place `app.use(apiMetrics())` early in your main application's middleware stack, ideally before other route handlers or dedicated error-handling middleware.
affects: >=2.1.3
gotchaThe default metrics collection interval for process metrics is 10 seconds. If your application's behavior changes rapidly, you might need to adjust this interval, which could impact resource usage.
fix
Configure the `defaultMetricsInterval` option when initializing `apiMetrics`: `app.use(apiMetrics({ defaultMetricsInterval: 5000 }))` for 5-second intervals. Ensure Prometheus scrape intervals are aligned.
affects: *
Errors
Common errors & fixes
TypeError: apiMetrics is not a function
Attempting to import the CommonJS module using ESM named import syntax (e.g., `import { apiMetrics } from '...'`) or incorrectly using `require` for an ESM default export.
fix
For CommonJS, use `const apiMetrics = require('prometheus-api-metrics');`. For ESM, use `import apiMetrics from 'prometheus-api-metrics';` as it is a default export.
Cannot find module 'prom-client'
The `prom-client` package is a peer dependency and must be installed separately, but it is missing from your project's `node_modules`.
fix
Install the peer dependency: `npm install prom-client` or `yarn add prom-client`. Check the `prom-client` version compatibility in `package.json`.
Error: A metric with the name 'my_app_http_request_duration_seconds' has already been registered.
The `apiMetrics()` middleware or `prom-client`'s `collectDefaultMetrics()` has been initialized or called multiple times, leading to duplicate metric registrations.
fix
Ensure `apiMetrics()` and `collectDefaultMetrics()` are called only once during your application's setup phase. Verify that you don't have multiple instances of the middleware running.
Metrics not accessible at /metrics (or custom path)
The `apiMetrics` middleware has not been correctly registered with your application, or the server is not listening on the expected port, or the `metricsPath` option was configured differently.
fix
Verify that `app.use(apiMetrics())` is properly placed in your Express/Koa application. Confirm the server is running and check for any custom `metricsPath` configuration in the middleware options.
Upgrade
Version history
4.0.0latest on npm
Audit
Dependencies
prom-clientrequiredCore Prometheus client library for metric collection and exposition.
Agent activity
15 hits · last 30 days
node
14
OpenAI (training)
1
Resources
prometheus-api-metrics — npm install prometheus-api-metrics · libregistry