Koa Request ID Middleware

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

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.

error TypeError: app.use is not a function
cause This error typically occurs when attempting to use `koa-requestid` with an application framework that is not Koa (e.g., Express) or with an outdated Koa 1.x application that expects generator-based middleware.
fix
Ensure your application is built with Koa 2.x or newer. If you are using Express or another framework, 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'
cause This is a TypeScript error indicating that the Koa `Context`'s `state` object does not have a defined `id` property, which `koa-requestid` adds at runtime.
fix
To resolve this, you need to augment Koa's 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.
cause This error can occur if the package is not installed, there's a typo in the import path, or TypeScript cannot locate the type definitions (e.g., for versions prior to 2.0.2 or if `@types/koa-requestid` is missing when needed).
fix
First, ensure the package is installed: 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.
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`.
fix Ensure your Koa application is using Koa 2.x or later. Migrate any generator-based middleware to `async/await` functions. Alternatively, if upgrading Koa is not feasible, use `koa-requestid` versions prior to 2.0.0 (e.g., `^1.0.0`).
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.
fix Upgrade your Node.js environment to version 20 or newer. If forced to use an older Node.js version, consider using an older version of `koa-requestid` if compatible or evaluate alternative request ID middleware for Koa.
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.
fix If `koa-requestid` is configured to read custom IDs from client input (e.g., `header` or `query` options are set), add custom middleware *before* `koa-requestid` to validate or sanitize these inputs according to your application's security requirements.
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.
fix Upgrade to `koa-requestid@2.0.2` or newer to leverage official TypeScript definitions. If using older versions, you may need to install `@types/koa-requestid` if available, or declare the module manually.
npm install koa-requestid
yarn add koa-requestid
pnpm add koa-requestid

This quickstart demonstrates how to integrate `koa-requestid` into a TypeScript Koa application, configure custom headers/query parameters, and access the generated or provided request ID from `ctx.state.id`.

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');
});