Skip to content
EventFabric CQRS Framework

CorrelationID Middleware

The CorrelationID middleware extracts a correlation ID from incoming request headers or generates a new one using ULID. This ID is stored in the Hono context and optionally added to response headers, enabling request tracing across your application.

An in Depth Example

This guide also has an in depth example of a working application built with EventFabric. Combining DDD, CQRS and Event Sourcing.

Check out the In Depth Example page to learn how everything is connected and works out in a real-world application.

import { Hono } from "hono";
import { correlationId, getCorrelationId } from "@nimbus-cqrs/hono";

const app = new Hono();

// Add the middleware
app.use(correlationId());

app.get("/", (c) => {
    const id = getCorrelationId(c);
    return c.json({ correlationId: id });
});

The middleware checks the following headers in order of priority:

PriorityHeader Name
1x-correlation-id
2x-request-id
3request-id

If none of these headers are present, a new ULID is generated.

OptionTypeDefaultDescription
addToResponseHeadersbooleantrueAdd the correlation ID to response headers
responseHeaderNamestring"x-correlation-id"The header name to use in the response
import { correlationId } from "@nimbus-cqrs/hono";

// Custom configuration
app.use(
    correlationId({
        addToResponseHeaders: true,
        responseHeaderName: "x-request-id",
    })
);

Use the getCorrelationId() helper function to retrieve the correlation ID from the Hono context:

import { getCorrelationId } from "@nimbus-cqrs/hono";

app.get("/users/:id", async (c) => {
    const correlationId = getCorrelationId(c);

    // Use in logging
    logger.info({
        message: "Fetching user",
        correlationId,
    });

    // Pass to commands/queries
    const command = createCommand({
        type: "get-user",
        correlationid: correlationId,
        data: { id: c.req.param("id") },
    });

    return c.json(await router.route(command));
});