{"id":16337,"library":"datadog-metrics","title":"Datadog Metrics Reporter","description":"datadog-metrics is a Node.js library designed for buffering and reporting application metrics to Datadog via its HTTP API. It supports common metric types including gauges, increments, histograms, and distributions. The current stable version is 0.12.1, with a pre-release (0.13.0-pre.1) indicating a future focus on reducing the bundle size and resource footprint by decoupling from heavier official Datadog clients. The library features automatic metric flushing before process exit (since v0.12.1), automatic retries for failed submissions (since v0.12.0), and includes built-in TypeScript definitions (since v0.11.0). Its release cadence is moderate, with significant feature updates often accompanied by breaking changes.","status":"active","version":"0.12.1","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/dbader/node-datadog-metrics","tags":["javascript","datadog","metrics","stats","typescript"],"install":[{"cmd":"npm install datadog-metrics","lang":"bash","label":"npm"},{"cmd":"yarn add datadog-metrics","lang":"bash","label":"yarn"},{"cmd":"pnpm add datadog-metrics","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Used for interacting with the Datadog API in versions prior to 0.13.0. This dependency is slated for removal in v0.13.0 and newer to reduce package size.","package":"datadog-api-client","optional":false}],"imports":[{"note":"Initializes the global metrics object. For CommonJS, you'd typically `const metrics = require('datadog-metrics'); metrics.init(...)` then use `metrics.gauge` etc.","wrong":"const init = require('datadog-metrics').init;","symbol":"init","correct":"import { init } from 'datadog-metrics';"},{"note":"This is a named export for creating independent metric loggers. Correctly typed as a class since v0.11.4.","wrong":"import BufferedMetricsLogger from 'datadog-metrics';","symbol":"BufferedMetricsLogger","correct":"import { BufferedMetricsLogger } from 'datadog-metrics';"},{"note":"After calling `metrics.init()`, functions like `metrics.gauge()` and `metrics.increment()` are available directly on the imported `metrics` object.","wrong":"import metrics from 'datadog-metrics';","symbol":"metrics global object","correct":"import * as metrics from 'datadog-metrics';"}],"quickstart":{"code":"import { init, BufferedMetricsLogger } from 'datadog-metrics';\n\n// Initialize the global metrics object\ninit({\n  apiKey: process.env.DD_API_KEY ?? '',\n  appKey: process.env.DD_APP_KEY ?? '', // Optional, for advanced features/error details\n  host: 'my-app-server',\n  prefix: 'my_app.',\n  tags: ['env:production', 'region:us-east-1'],\n  flushIntervalSeconds: 15,\n  // Optional: configure to use custom logger for more control\n  // logger: console,\n});\n\n// Send some metrics using the global instance\nmetrics.gauge('user_sessions', 1234, ['browser:chrome']);\nmetrics.increment('request_count', 1, ['status:200']);\nmetrics.histogram('api_response_time', 150.5, ['endpoint:/data']);\nmetrics.distribution('task_duration_ms', 55.2, ['task_name:process_batch']);\n\nconsole.log('Metrics sent via global instance.');\n\n// Create and use a separate buffered logger instance\nconst customLogger = new BufferedMetricsLogger({\n  apiKey: process.env.DD_API_KEY ?? '',\n  host: 'custom-worker',\n  prefix: 'worker_process.',\n  tags: ['worker_id:42', 'queue:high_prio'],\n});\n\ncustomLogger.gauge('queue_depth', 5);\ncustomLogger.increment('job_processed');\nconsole.log('Metrics sent via custom logger instance.');\n\n// Manual flush (optional, auto-flush on exit since v0.12.1)\n// In a real application, you might want to wait for these promises\nPromise.all([\n  metrics.flush(),\n  customLogger.flush()\n]).then(() => {\n  console.log('All metrics manually flushed.');\n}).catch(err => {\n  console.error('Error flushing metrics:', err);\n});","lang":"typescript","description":"Demonstrates initializing the global metrics reporter and sending various metric types (gauge, increment, histogram, distribution). Also shows how to create and use a separate BufferedMetricsLogger instance for isolated metric collection, and how to perform an explicit flush operation."},"warnings":[{"fix":"Ensure your Node.js environment is at least v14.0.0 before upgrading to v0.13.0 or later.","message":"The minimum required Node.js version has been bumped from v12.0.0 to v14.0.0.","severity":"breaking","affected_versions":">=0.13.0-pre.1"},{"fix":"Update any error handling logic that inspects the `code` property of `AuthorizationError` instances to use the new string literal.","message":"The `code` property on `AuthorizationError` instances has been changed to `DATADOG_METRICS_AUTHORIZATION_ERR`.","severity":"breaking","affected_versions":">=0.13.0-pre.1"},{"fix":"For critical metrics or specific exit scenarios, explicitly call `metrics.flush()` and await its completion before `process.exit()` or when `flushIntervalSeconds` is zero.","message":"Since v0.12.1, metrics are automatically flushed before the process exits. However, if `flushIntervalSeconds` is set to `0` or `process.exit()` is called, manual flushing via `metrics.flush()` is still required to guarantee all metrics are sent.","severity":"gotcha","affected_versions":">=0.12.1"},{"fix":"Refactor any asynchronous operations to use Promise-based syntax (e.g., `async/await` or `.then/.catch`) instead of passing callback functions.","message":"Asynchronous actions, such as `flush()`, now exclusively use Promises instead of callbacks. Callback arguments are no longer supported.","severity":"breaking","affected_versions":">=0.12.0"},{"fix":"If you are directly using `new DatadogReporter(...)`, update your constructor call to pass a single options object.","message":"The `DatadogReporter` constructor now requires an options object instead of positional arguments. This primarily affects users directly instantiating the reporter.","severity":"breaking","affected_versions":">=0.12.0"},{"fix":"Remove `@types/datadog-metrics` from your `package.json` and `npm install` or `yarn install`.","message":"Built-in TypeScript definitions were introduced in v0.11.0. The separate `@types/datadog-metrics` package is no longer needed and should be removed from your `devDependencies`.","severity":"deprecated","affected_versions":">=0.11.0"},{"fix":"Ensure you are using the `aggregates` option when configuring histogram behavior, not `aggregations`.","message":"The option for configuring histogram aggregates was previously misdocumented and typed as `aggregations`. It has been corrected to `aggregates`.","severity":"gotcha","affected_versions":"<0.11.2"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Set the `DD_API_KEY` environment variable or explicitly pass an `apiKey` string in the options object to `metrics.init()` or `new BufferedMetricsLogger()`.","cause":"The Datadog API key was not provided during initialization.","error":"Error: Datadog API key is not configured. Set the 'DD_API_KEY' environment variable or pass an 'apiKey' option."},{"fix":"Ensure `metrics.init()` is called and completes successfully before any other metric reporting functions are invoked on the global `metrics` object.","cause":"Attempted to use metric reporting functions (e.g., `metrics.gauge()`) before `metrics.init()` has been called.","error":"TypeError: metrics.gauge is not a function (or increment/histogram/distribution)"},{"fix":"Ensure `metrics.init()` is called only once in your application's lifecycle. If you need multiple independent loggers, use `new BufferedMetricsLogger()` instead.","cause":"The `metrics.init()` function was called multiple times, which is not allowed for the global metrics object.","error":"Error: The 'metrics' object has already been initialized."}],"ecosystem":"npm"}