Koa Datadog Metrics Middleware
raw JSON →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.
Common errors
error TypeError: app.use is not a function ↓
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) ↓
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 ↓
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. Warnings
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`. ↓
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). ↓
Install
npm install koa-datadog-middleware yarn add koa-datadog-middleware pnpm add koa-datadog-middleware Imports
- ddog wrong
import ddog from 'koa-datadog-middleware'correctconst ddog = require('koa-datadog-middleware') - ddog() (middleware instantiation) wrong
app.use(ddog)correctapp.use(ddog(config)) - ctx.state.datadog (custom tags)
ctx.state.datadog = { my_tag: 'value' };
Quickstart
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