Accessing the correlation ID

Updated Jul 20, 2026

The middleware provides two ways to access the current request's correlation ID. Both methods always return the same value for the duration of a request, because the middleware sets them from the same source in process_request.

Via `req.context.correlation_id`

Within Falcon responders, hooks, and any code that has access to the req object, the correlation ID is available directly on the request context:

class MyResource:
    def on_get(self, req, resp):
        cid = req.context.correlation_id
        resp.media = {"correlation_id": cid}

This is the simplest approach when req is already in scope.

Via `correlation_id_var.get()`

In code that does not have access to the Falcon req object — such as logging filters, utility functions, and downstream service clients — use the context variable instead:

from falcon_correlate import correlation_id_var


def build_downstream_headers():
    cid = correlation_id_var.get()
    if cid is not None:
        return {"X-Correlation-ID": cid}
    return {}

When to use each method

Method Use when
req.context.correlation_id Code already has access to the Falcon req object (responders, hooks, middleware). Simpler and more explicit.
correlation_id_var.get() Code does not have access to req (logging filters, utility functions, service clients, Celery tasks). Framework-agnostic.

Both methods are kept in sync by the middleware. There is no need to choose one exclusively — use whichever is most convenient for the call site.

echo_header_in_response

Whether to copy the resolved correlation ID into the configured response header during process_response.

  • Type: bool
  • Default: True

When enabled, the middleware uses the same header_name value for both the incoming request header and the outgoing response header. It only echoes a correlation ID that this middleware established during process_request; a pre-existing req.context.correlation_id from other code is not echoed. If the response already has a header with that name, it is overwritten with the resolved correlation ID.

# Disable echoing correlation ID in responses
middleware = CorrelationIDMiddleware(echo_header_in_response=False)

Example request and response:

GET /hello HTTP/1.1
Host: api.example.com
X-Correlation-ID: 7f0c8a2f1b2e4a3b9d0f5c6e7a8b9c0d

HTTP/1.1 200 OK
Content-Type: application/json
X-Correlation-ID: 7f0c8a2f1b2e4a3b9d0f5c6e7a8b9c0d

With echo_header_in_response=False, the request still gets a correlation ID internally, but the response omits the correlation header.