Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Prometheus to next.js?

I should use prom-client in my nextjs app. but I have no idea for it. I cant find any example for it

I want to add Prometheus with prom-client to my nextjs app. I should use histogram in getServerSideProps function. this is my current code:

// api/metrics.js
import { promRegister } from "Utils/promClient";
export default async function handler(req, res) {

  const client = await import("prom-client");
  const register = new client.Registry();

  const collectDefaultMetrics = client.collectDefaultMetrics;
  collectDefaultMetrics({ register });

    res.setHeader("Content-Type", promRegister.contentType);

    res.status(200).send(await promRegister.metrics());
// Utils/promClient.js
import { register, Histogram, collectDefaultMetrics } from "prom-client";

register.clear();

export const performanceMeasurHistogram = new Histogram({
  name: "getData",
  help: "getData",
  labelNames: ["status", "controller", "pageUrl"],
  buckets: [0.5 ,1, 5, 10, 20, 50, 100],
});
const collectDefault = collectDefaultMetrics;
collectDefault();

export const promRegister = register;
// page/index.js
export async function getServerSideProps({ res, req }) {

  const timer = performanceMeasurHistogram.startTimer();
  const data = await axios.get(...)
  timer({
    status: data.status,
    controller: data.request.path,
    pageUrl:"/",
  });
}

like image 441
Kamran Davar Avatar asked Oct 19 '25 23:10

Kamran Davar


2 Answers

You can try to install the npm package:

npm install prom-client

Then, you can try create a new file called prometheus.js in your Next.js pages directory:

import { register, collectDefaultMetrics } from 'prom-client';

// Create a custom counter metric for counting HTTP requests
const httpRequestCount = new Counter({
  name: 'http_requests_total',
  help: 'Total number of HTTP requests',
  labelNames: ['method', 'route', 'statusCode'],
});

// Initialize Prometheus metrics collection
collectDefaultMetrics();

// Export a middleware function to expose a /metrics endpoint
export default function (req, res) {
  res.set('Content-Type', register.contentType);
  res.end(register.metrics());
}

// Export the custom counter metric for use in your application
export { httpRequestCount };

Then import httpRequestCount:

import { httpRequestCount } from './prometheus';

export default function handler(req, res) {
  // Increment the httpRequestCount metric for this request
  httpRequestCount.inc({
    method: req.method,
    route: req.url,
    statusCode: res.statusCode,
  });

  // Handle the request and send the response
  // ...

Add a route for the /metrics endpoint in your next.config.js file:

module.exports = {
  async rewrites() {
    return [
      {
        source: '/metrics',
        destination: '/prometheus',
      },
    ];
  },
};

Then you done!

you can start your Next.js application and navigate to http://localhost:3000/metrics to view the Prometheus metrics.

like image 98
yanir midler Avatar answered Oct 23 '25 00:10

yanir midler


The answer above will not work as every file in pages directory us expected to run client side. I would change it as follows:

the handler function should be in api/metrics

import { NextApiRequest, NextApiResponse } from "next";
import { register, collectDefaultMetrics } from "prom-client";

collectDefaultMetrics({});

export default async function handler(_: NextApiRequest, res: NextApiResponse<any>) {
  res.setHeader('Content-type', register.contentType);
  res.send(await register.metrics());
}

while the config should be changed to the following:

module.exports = {
  async rewrites() {
    return [
      {
        source: '/metrics',
        destination: '/api/metrics',
      },
    ];
  },
};
like image 32
Inbar Sletean Avatar answered Oct 22 '25 22:10

Inbar Sletean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!