Starlette Context

0.5.1 · active · verified Sat Apr 11

Starlette Context is a middleware for Starlette that provides a request-scoped data store, allowing you to store and access context data throughout the request lifecycle. It is commonly used to enrich logs with request-specific identifiers like `x-request-id` or `x-correlation-id` without explicit parameter passing. The current version is 0.5.1, released on February 28, 2026, and the library maintains an active release cadence.

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up `ContextMiddleware` with basic plugins (`RequestIdPlugin`, `CorrelationIdPlugin`) and access/modify the `context` object within a Starlette route. When you access '/', the response will include the generated request and correlation IDs, along with any custom data added to the context. To run, save as `example.py` and execute `uvicorn example:app --port 8000`.

import uvicorn
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette_context import context, plugins
from starlette_context.middleware import ContextMiddleware

async def homepage(request):
    # Access and modify context data
    context["user_id"] = "123"
    context["custom_data"] = "Hello from Starlette Context!"
    return JSONResponse(context.data)

routes = [
    Route("/", endpoint=homepage)
]

middleware = [
    Middleware(
        ContextMiddleware,
        plugins=(
            plugins.RequestIdPlugin(),
            plugins.CorrelationIdPlugin(),
        )
    )
]

app = Starlette(routes=routes, middleware=middleware)

if __name__ == "__main__":
    # Run with `uvicorn example:app --port 8000`
    uvicorn.run(app, host="0.0.0.0", port=8000)

view raw JSON →