Providing complete Express middleware with Prometheus metrics and basic auth
I'm creating a self-contained Node.js Express example using prom-client to manually implement a request duration histogram and a response status counter, along with a basic-auth-protected /metrics endpoint that reads credentials from environment variables.
Below is a minimal Express setup that:
- Uses
prom-client directly (no express-prometheus-bundle).
- Exposes a
Histogram for request durations (with custom buckets) and a Counter for status codes.
- Protects the
/metrics endpoint with basic auth.
// metrics.js
const express = require('express');
const client = require('prom-client');
const app = express();
// --- Prometheus Metrics ---
const register = new client.Registry();
// Optional: collect default Node.js process metrics
client.collectDefaultMetrics({ register });
// Histogram for request duration (in seconds)
const httpRequestDurationSeconds = new client.Histogram({
name: 'http_request_duration_seconds',
help: 'Duration of HTTP requests in seconds',
labelNames: ['method', 'path', 'status_code'],
buckets: [0.005, 0.01, 0.05, 0.1, 0.3, 0.5, 1, 2, 5, 10], // Customize as needed
});
// Counter for status codes
const httpResponseStatus = new client.Counter({
name: 'http_response_status_total',
help: 'Count of HTTP responses by status code',
labelNames: ['method', 'path', 'status_code'],
});
register.registerMetric(httpRequestDurationSeconds);
register.registerMetric(httpResponseStatus);
// --- Middleware to record metrics ---
function promMiddleware(req, res, next) {
const startHrTime = process.hrtime();
// Express finishes the response -> measure duration & increment counters
res.on('finish', () => {
// Compute duration in seconds
const diff = process.hrtime(startHrTime);
const durationSeconds = diff[0] + diff[1] / 1e9;
// Use a low-cardinality path label. Fallback if not found.
const path = (req.route && req.route.path) || req.originalUrl || 'unknown';
// Observe the request duration
httpRequestDurationSeconds.observe(
{ method: req.method, path, status_code: res.statusCode },
durationSeconds
);
// Increment status counter
httpResponseStatus.inc({ method: req.method, path, status_code: res.statusCode });
});
next();
}
// Attach the middleware to all routes
app.use(promMiddleware);
// Example route
app.get('/hello', (req, res) => {
res.send('Hello, World!');
});
// --- Basic auth for /metrics ---
const METRICS_USER = process.env.METRICS_USER || 'admin';
const METRICS_PASS = process.env.METRICS_PASS || 'secret';
function basicAuth(req, res, next) {
const auth = req.headers.authorization || '';
const token = auth.split(' ')[1] || '';
const [user, pass] = Buffer.from(token, 'base64').toString().split(':');
if (user === METRICS_USER && pass === METRICS_PASS) {
return next();
}
res.set('WWW-Authenticate', 'Basic realm="metrics"');
return res.status(401).send('Authentication required.');
}
app.get('/metrics', basicAuth, async (_req, res) => {
res.set('Content-Type', register.contentType);
res.end(await register.metrics());
});
// Start server
const port = process.env.PORT || 3000;
app.listen(port, () => {
// Optionally log that metrics are live
console.log(`Server listening on port ${port}`);
console.log(`Metrics exposed on /metrics (basic auth protected).`);
});
module.exports = app;
How it works
- Histogram (
http_request_duration_seconds) observes each request duration in seconds, labeled by method, path, and status_code.
- Counter (
http_response_status_total) counts responses by status code (also labeled by method and path).
- A simple basic auth middleware protects
/metrics. Credentials are read from METRICS_USER / METRICS_PASS.
- The
promMiddleware measures the time from request start to finish and updates both metrics.
Adjust buckets, metric names, and labels as needed for your environment.