Koa Request ID Middleware
raw JSON →koa-requestid is a lightweight Koa middleware designed to automatically generate and attach a unique request ID to incoming HTTP requests. By default, it uses UUIDv4 for generation and exposes the ID via the `Request-Id` response header, also storing it in `ctx.state.id` for easy access within downstream middleware or route handlers. The current stable version is 2.3.0, with minor updates released periodically based on maintenance needs and dependency updates, as seen in the recent changelogs. Key differentiators include its simplicity, minimal configuration overhead, and the ability to accept custom request IDs from specified request headers or query parameters, which is particularly useful for debugging or tracing across services. Since version 2.0.2, it ships with comprehensive TypeScript definitions, enhancing developer experience for TypeScript-based Koa applications. It is specifically built for Koa applications, leveraging Koa's middleware pattern and context object.
Common errors
error TypeError: app.use is not a function ↓
koa-requestid is not compatible; you'll need a request ID middleware specific to that framework. error Property 'id' does not exist on type 'DefaultState' ↓
DefaultState interface in your TypeScript project. Add a declaration like declare module 'koa' { interface DefaultState { id: string; } } in a global .d.ts file or at the top of a relevant .ts file. error Cannot find module 'koa-requestid' or its corresponding type declarations. ↓
npm install koa-requestid or yarn add koa-requestid. Verify the import path from 'koa-requestid'. If using an older version of koa-requestid (<2.0.2) in TypeScript, consider upgrading or installing @types/koa-requestid if available. Warnings
breaking Version 2.0.0 introduced a significant breaking change by updating to `koa@2.0.1`. This means the middleware now expects Koa 2.x style `async/await` middleware functions, diverging from Koa 1.x's generator-based middleware. Applications still using Koa 1.x will need to upgrade Koa or remain on an older version of `koa-requestid`. ↓
breaking The package's `engines.node` field specifies a minimum Node.js version of `20`. Running `koa-requestid` on older Node.js versions may lead to unexpected behavior or failures due to modern JavaScript features or API usage. ↓
gotcha When `koa-requestid` accepts a custom request ID via a header or query parameter, the input value is NOT sanitized. Malicious or malformed input could potentially be exposed in logs or other system components. Developers must implement their own sanitization or validation if accepting untrusted input for request IDs. ↓
gotcha TypeScript definitions were added in version 2.0.2. Prior versions (e.g., 2.0.0, 2.0.1) do not provide official type definitions, which can lead to type errors or require manual `any` assertions in TypeScript projects. ↓
Install
npm install koa-requestid yarn add koa-requestid pnpm add koa-requestid Imports
- requestId wrong
import { requestId } from 'koa-requestid';correctimport requestId from 'koa-requestid'; - requestId (CommonJS)
const requestId = require('koa-requestid'); - DefaultState (Koa Context Augmentation)
declare module 'koa' { interface DefaultState { id: string; } }
Quickstart
import Koa from 'koa';
import requestId from 'koa-requestid';
// Augment Koa's Context type to include 'id' in state
declare module 'koa' {
interface DefaultState {
id: string;
}
}
const app = new Koa();
// Apply the middleware with custom options
app.use(requestId({
expose: 'X-Request-ID', // Custom header for the response
header: 'X-Client-Trace-Id', // Custom header to read from request
query: 'traceId' // Custom query parameter to read from request
}));
// Define a Koa route that uses the request ID
app.use(async (ctx) => {
const reqId = ctx.state.id; // Access the generated or provided request ID
console.log(`[${reqId}] Incoming request for ${ctx.path}`);
ctx.body = `Hello! Your unique request ID is: ${reqId}`;
});
const port = 3000;
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
console.log('Test with:');
console.log(' curl -v http://localhost:3000');
console.log(' curl -v -H "X-Client-Trace-Id: my-app-123" http://localhost:3000');
console.log(' curl -v http://localhost:3000?traceId=external-abc');
});