{"id":17742,"library":"koa-datadog-middleware","title":"Koa Datadog Metrics Middleware","description":"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.","status":"active","version":"1.2.1","language":"javascript","source_language":"en","source_url":"https://github.com/topfreegames/koa-datadog-middleware","tags":["javascript","koa","nodejs","datadog","monitoring","metrics"],"install":[{"cmd":"npm install koa-datadog-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add koa-datadog-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add koa-datadog-middleware","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary usage pattern shown in documentation is CommonJS `require`. While ES modules may work with bundlers, `require` is the officially documented approach for v1.x.","wrong":"import ddog from 'koa-datadog-middleware'","symbol":"ddog","correct":"const ddog = require('koa-datadog-middleware')"},{"note":"The imported `ddog` is a function that, when called, returns the actual Koa middleware. It expects an optional configuration object as its argument.","wrong":"app.use(ddog)","symbol":"ddog() (middleware instantiation)","correct":"app.use(ddog(config))"},{"note":"To add custom tags to metrics for a specific request, assign an object to `ctx.state.datadog` within your route or preceding middleware. These tags will be merged with global tags.","symbol":"ctx.state.datadog (custom tags)","correct":"ctx.state.datadog = { my_tag: 'value' };"}],"quickstart":{"code":"const Koa = require('koa');\nconst ddog = require('koa-datadog-middleware');\n\nconst app = new Koa();\n\n// Configure the Datadog middleware\n// Use environment variables for sensitive or deployment-specific configurations\nconst datadogConfig = {\n  host: process.env.DD_AGENT_HOST || 'localhost', \n  port: parseInt(process.env.DD_AGENT_PORT || '8125', 10),\n  prefix: 'my_koa_app.', // Metrics will be prefixed with 'my_koa_app.'\n  globalTags: ['env:development', 'service:web'], // Tags added to every metric\n  errorHandler: (error) => {\n    console.error('Datadog middleware encountered an error:', error.message);\n  }\n};\n\n// Register the Datadog middleware\napp.use(ddog(datadogConfig));\n\n// Example routes\napp.use(async (ctx, next) => {\n  if (ctx.path === '/status') {\n    // Add request-specific tags\n    ctx.state.datadog = {\n      endpoint: '/status',\n      custom_status: 'ok'\n    };\n    ctx.body = 'Service is running.';\n    ctx.status = 200;\n  } else if (ctx.path === '/error-route') {\n    ctx.throw(500, 'Something went wrong!');\n  } else {\n    ctx.body = 'Hello from Koa!';\n    ctx.status = 200;\n  }\n  await next(); // Essential to allow downstream middleware (like Datadog) to process\n});\n\n// Catch-all error handler for Koa to ensure errors are logged and middleware can process\napp.on('error', (err, ctx) => {\n  console.error('Server error detected:', err, ctx);\n});\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => {\n  console.log(`Koa server listening on http://localhost:${PORT}`);\n  console.log(`Datadog metrics will be sent to ${datadogConfig.host}:${datadogConfig.port}`);\n});\n\n// To run this example:\n// 1. npm install koa koa-datadog-middleware\n// 2. Set environment variables if needed: e.g., DD_AGENT_HOST=127.0.0.1 DD_AGENT_PORT=8125 node your-app.js\n// 3. Access: http://localhost:3000/status or http://localhost:3000/error-route","lang":"javascript","description":"Demonstrates basic Koa application setup with `koa-datadog-middleware`, including configuration using environment variables, adding custom per-request tags, and basic error handling."},"warnings":[{"fix":"If dynamic DNS resolution or frequent host changes are required, explicitly set `cacheDns: false` in the middleware configuration.","message":"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`.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"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).","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"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()`.","cause":"The Koa application instance has not been correctly initialized, or `app` is not a Koa application object.","error":"TypeError: app.use is not a function"},{"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).","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.","error":"Datadog agent not receiving metrics (no data appearing in Datadog UI)"},{"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.","cause":"The `koa-datadog-middleware` module was not correctly imported or required, or the variable name is incorrect.","error":"ReferenceError: ddog is not defined"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}