prom-client: Simple counter fails on Next.js -- Avoid using Node.js-specific APIs
Hi, I know this library is supposed to be framework agnostic, but it seems to be generating a bad interaction with Next.js. I have a counter defined like this:
let httpRequestsTotal = new client.Counter({
name: "http_requests_total",
help: "Total number of HTTP requests",
labelNames: ["method", "route", "statusCode"],
})
This counter works well if used from within an API route for example. Thing is, I want it to catch every single request, so I use it where it makes most sense, in a middleware:
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { metrics } from "@/modules/common/metrics";
export function middleware(request: NextRequest) {
NextResponse.next();
console.log(`${request.method} -- ${request.url}`);
metrics.httpRequestsTotal.inc({ method: request.method, route: request.url });
}
Doing this throws the following error:
Server Error
Error: A Node.js API is used (process.uptime) which is not supported in the Edge Runtime.
This might not make a lot of sense if you don’t know Next.js but some code, like the middleware, runs on a different JS runtime where it cannot be assumed that Node.js global APIs are available. My main question is: why would a counter.inc() call process.uptime? Seems unnecessary.
Ideally, no Node.js specific APIs should be used, only standard Web APIs, unless specifically required (and being able to opt-out).
thanks for the help
About this issue
- Original URL
- State: open
- Created 3 years ago
- Reactions: 9
- Comments: 20
@harry-gocity can you share some examples using
@vercel/oteland@opentelemetry?FWIW I’ve somewhat started to give up with this lib - we’re now using
@vercel/oteland@opentelemetrypackages instead, and scraping metrics with a prometheus exporter instead. The integration with Next.js is much cleaner, we have better tracing on GSSP (segmented by component load, fetch calls, and render) and we don’t have to jump through bundling hoops to get a build passing. The only thing we still use this library for is the default metrics, the custom ones are all being migrated.After a lot of debugging I finally found what was missing. For anyone who has a similar issue, in my
next.config.jsI needed both theinstrumentationHookand:and then calling
await register.metrics()works within an API handler.Also in relation to the original issue, while you can’t increment a counter directly within the
middleware.tsfile, you can call to an exposed API from the middleware (example/pages/api/metrics/counter.ts) and increment this way.@santosguilherme
I suppose this might help you.
https://github.com/vercel/next.js/discussions/16205#discussioncomment-9360516
Thanks @harry-gocity I was missing the
instrumentationHookflag in the next config file. Two questions:await prom.register.metrics();at the end of this register function?At the end of the register block I am able to call
getSingleMetric()and it returns the correct value, however when I try to do the same thing in an API route I getundefined:Here is my exact
instrumentation.tsfile:We’ve since upgraded to next 14 (still pages dir) and now have an
instrumentation.tsthat looks like this:We don’t call
collectDefaultMetricsanywhere else. And to access the metrics, we useregister.getSingleMetricrather than a reference to the created metric directly.For simple default metrics, creating an api route works well in Next.js:
As for using
prom-clientanywhere else I’ve only been able to do so ingetServerSideProps, as the middleware expects Vercel’s edge runtime compatability. Quite a lot of (imo understandably) unhappy discussion about it here. It’s very annoying for us as we are running dockerised node, we have nothing but the node runtime, and we get these edge runtime warnings.In the end my
getServerSidePropsall have a wrapper that looks something like this:That is used like this
I did find that the
observedGetServerSidePropshad to be defined in another file, if I used something similar in the actual pages directory Next would complain at build, the same as your issue @pablote. I’m not entirely sure why a separate module gets around the warning, but Next doesn’t mind 🤷🏼♂️I would be very interested in improvements to allow us to use the middleware in Next rather than this wrapper, as currently we cannot use
prom-clientfor any statically optimised pages (nogetServerSideProps/getStaticProps). And the wrapping isn’t ideal, it’s very all-or-nothing for adding metrics to a page.Making
requires lazy and migrating toURLglobal should both be fine to land at least. Let’s start with that? Thenfetchis a natural one to target after that. Node 16 is EOL shortly, so we might get away with using globalfetchas well, but I wanna evaluate that separately