Prometheus Metrics in TypeScript: Complete Guide to client.js

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Prometheus Metrics in TypeScript: Practical Guide



Prometheus is a powerful open-source monitoring and alerting system. For integration with TypeScript applications, the prom-client (Prometheus Client) library is used. It allows collecting, aggregating, and exporting metrics in a format understandable by the Prometheus server. In this article, we will thoroughly examine how to work with Prometheus metrics in TypeScript, including metric types, code examples, and best practices.



Installation and Setup



First, install the package via npm:

npm install prom-client


For TypeScript, you will also need to install the types:

npm install @types/prom-client --save-dev


After installation, create a metrics.ts file to initialize the client:



import client from 'prom-client';

// Enable collection of default metrics (GC, memory, CPU)const collectDefaultMetrics = client.collectDefaultMetrics;collectDefaultMetrics({ timeout: 5000 });

// Create a registry to store metricsconst register = client.register;

export { client, register };


Main Prometheus Metric Types



Prometheus supports four main metric types. Let's examine each with TypeScript examples.



1. Counter

Used for counting events that only increase (requests, errors).



import { Counter } from 'prom-client';

const httpRequestsTotal = new Counter({ name: 'http_requests_total', help: 'Total number of HTTP requests', labelNames: ['method', 'path', 'status_code'],});

// Increment the counter on requesthttpRequestsTotal.inc({ method: 'GET', path: '/api', status_code: 200 });httpRequestsTotal.inc({ method: 'POST', path: '/users', status_code: 201 }, 2); // +2


2. Gauge

Can increase and decrease. Used for current values (memory, queue).



import { Gauge } from 'prom-client';

const memoryUsageGauge = new Gauge({ name: 'memory_usage_bytes', help: 'Current memory usage in bytes',});

// Set a valuememoryUsageGauge.set(process.memoryUsage().heapUsed);

// Change by deltamemoryUsageGauge.inc(1024); // +1KBmemoryUsageGauge.dec(512); // -512B


3. Histogram

Measures the distribution of values (e.g., response time).



import { Histogram } from 'prom-client';

const httpRequestDuration = new Histogram({ name: 'http_request_duration_seconds', help: 'Duration of HTTP requests in seconds', labelNames: ['method', 'route'], buckets: [0.1, 0.3, 0.5, 1, 2, 5], // bucket boundaries});

// Observe a valueconst start = Date.now();// ... request processing ...httpRequestDuration.observe( { method: 'GET', route: '/api' }, (Date.now() - start) / 1000);


4. Summary

Similar to histogram, but calculates quantiles on the client side.



import { Summary } from 'prom-client';

const responseTimeSummary = new Summary({ name: 'response_time_summary_seconds', help: 'Response time summary in seconds', percentiles: [0.5, 0.9, 0.99], // quantiles});

responseTimeSummary.observe(0.42);responseTimeSummary.observe(0.35);


Exporting Metrics for Prometheus



Create a /metrics endpoint that will serve metrics in text format:



import express from 'express';import { register } from './metrics';

const app = express();

app.get('/metrics', async (req, res) => { try { res.set('Content-Type', register.contentType); res.end(await register.metrics()); } catch (err) { res.status(500).end(err); }});

app.listen(3000, () => console.log('Server running on port 3000'));


Now, upon a GET requ

Recommendations