Koa Datadog Metrics Middleware

raw JSON →
1.2.1 verified Thu Apr 23 auth: no javascript

koa-datadog-middleware is a Koa.js middleware designed for automatically reporting application performance metrics to Datadog via DogStatsD. It specifically tracks response times and request counts, categorizing them by HTTP status code, request path, and HTTP method. The middleware allows for the inclusion of custom tags, either through its initial configuration or dynamically by setting properties on `ctx.state.datadog` for individual requests. It leverages the `hot-shots` library internally for StatsD client functionality but critically overrides some default `hot-shots` configurations. The current stable version, 1.2.1, indicates a mature library focused on a specific integration, with a release cadence that suggests stability over frequent breaking changes. It differentiates itself by providing a ready-to-use Koa integration specifically for Datadog histograms without extensive boilerplate, making it straightforward to add basic observability to Koa applications.

error TypeError: app.use is not a function
cause The Koa application instance has not been correctly initialized, or `app` is not a Koa application object.
fix
Ensure you have const Koa = require('koa'); and const app = new Koa(); at the beginning of your file before attempting to use app.use().
error Datadog agent not receiving metrics (no data appearing in Datadog UI)
cause Incorrect host or port configuration for the Datadog agent, the agent is not running, or network firewall rules are blocking UDP traffic to the agent.
fix
Verify the host and port settings in your ddog middleware configuration match your Datadog agent's dogstatsd_stats_port and host. Check if the Datadog agent is running and accessible from your application's host. Ensure no firewall rules block UDP on the specified port (default 8125).
error ReferenceError: ddog is not defined
cause The `koa-datadog-middleware` module was not correctly imported or required, or the variable name is incorrect.
fix
Ensure you have const ddog = require('koa-datadog-middleware'); at the top of your file. If using ES modules in an environment that supports it, try import ddog from 'koa-datadog-middleware'; after verifying your setup.
gotcha The default value for the `cacheDns` option in `koa-datadog-middleware` is `true`. This differs from the underlying `hot-shots` library's default of `false`.
fix If dynamic DNS resolution or frequent host changes are required, explicitly set `cacheDns: false` in the middleware configuration.
gotcha The default value for the `maxBufferSize` option in `koa-datadog-middleware` is `1000`. This enables metric buffering by default, whereas the underlying `hot-shots` library defaults to `0` (no buffering).
fix If immediate metric transmission is critical and buffering is undesirable, explicitly set `maxBufferSize: 0` in the middleware configuration. Conversely, adjust `bufferFlushInterval` and `maxBufferSize` for optimal performance in high-throughput scenarios.
npm install koa-datadog-middleware
yarn add koa-datadog-middleware
pnpm add koa-datadog-middleware

Demonstrates basic Koa application setup with `koa-datadog-middleware`, including configuration using environment variables, adding custom per-request tags, and basic error handling.

const Koa = require('koa');
const ddog = require('koa-datadog-middleware');

const app = new Koa();

// Configure the Datadog middleware
// Use environment variables for sensitive or deployment-specific configurations
const datadogConfig = {
  host: process.env.DD_AGENT_HOST || 'localhost', 
  port: parseInt(process.env.DD_AGENT_PORT || '8125', 10),
  prefix: 'my_koa_app.', // Metrics will be prefixed with 'my_koa_app.'
  globalTags: ['env:development', 'service:web'], // Tags added to every metric
  errorHandler: (error) => {
    console.error('Datadog middleware encountered an error:', error.message);
  }
};

// Register the Datadog middleware
app.use(ddog(datadogConfig));

// Example routes
app.use(async (ctx, next) => {
  if (ctx.path === '/status') {
    // Add request-specific tags
    ctx.state.datadog = {
      endpoint: '/status',
      custom_status: 'ok'
    };
    ctx.body = 'Service is running.';
    ctx.status = 200;
  } else if (ctx.path === '/error-route') {
    ctx.throw(500, 'Something went wrong!');
  } else {
    ctx.body = 'Hello from Koa!';
    ctx.status = 200;
  }
  await next(); // Essential to allow downstream middleware (like Datadog) to process
});

// Catch-all error handler for Koa to ensure errors are logged and middleware can process
app.on('error', (err, ctx) => {
  console.error('Server error detected:', err, ctx);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Koa server listening on http://localhost:${PORT}`);
  console.log(`Datadog metrics will be sent to ${datadogConfig.host}:${datadogConfig.port}`);
});

// To run this example:
// 1. npm install koa koa-datadog-middleware
// 2. Set environment variables if needed: e.g., DD_AGENT_HOST=127.0.0.1 DD_AGENT_PORT=8125 node your-app.js
// 3. Access: http://localhost:3000/status or http://localhost:3000/error-route