Skip to content
Latchkey

prom-client Node "A metric with the name X has already been registered" in CI

The Node prom-client default registry throws if you create two metrics with the same name. Jest isolates modules per test file, so a module that constructs metrics at import time constructs them again for each file, colliding on the name.

What this error means

A test fails with "Error: A metric with the name http_requests_total has already been registered." typically when running the whole Jest suite, not one file.

node
Error: A metric with the name http_requests_total has already been registered.
    at Registry.registerMetric (node_modules/prom-client/lib/registry.js:...)

Common causes

Metrics constructed at module import time

A new client.Counter({ name: "http_requests_total" }) at module scope registers into the global registry. Re-importing the module (per test file) constructs it again with the same name.

The global registry persists across imports

prom-client uses a shared default register, so a stale metric from a prior import is still present when the module loads again.

How to fix it

Clear the registry between tests

  1. Call register.clear() in a beforeEach/afterEach so no stale metric lingers.
  2. Or guard construction so a metric is created only once.
  3. For isolation, construct metrics against a new Registry() per test.
test/setup.js
const client = require('prom-client');
afterEach(() => client.register.clear());

Reuse an existing metric if present

Look the metric up before creating it so a re-import does not register a duplicate.

metrics.js
const existing = client.register.getSingleMetric('http_requests_total');
const counter = existing || new client.Counter({ name: 'http_requests_total', help: 'h' });

How to prevent it

  • Clear or reset the prom-client registry between tests.
  • Construct each metric once, or reuse via getSingleMetric.
  • Use a dedicated Registry for tests to isolate state.

Frequently asked questions

What causes ""has already been registered""?
A new client.Counter({ name: "http_requests_total" }) at module scope registers into the global registry. Re-importing the module (per test file) constructs it again with the same name.
How do I fix "has already been registered"?
Clear the registry between tests

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card