Skip to content

@scoped doesn't work with async fastapi middleware #568

@slmnsh

Description

@slmnsh

Version

7.9.12

Steps to Reproduce

Middleware:

@posthog.scoped()
@app.middleware("http")
async def initialize_posthog_context(
    request: Request, call_next: Callable[[Request], Awaitable[Response]]
):
    user_id = get_current_user_safe(request)
    if user_id is not None:
        posthog.identify_context(user_id)
    return await call_next(request)

Route:

@router.get("/")
async def index():
    # ...
    posthog.capture("new_event")
    # ...

But if I do following middleware it works:

@app.middleware("http")
async def initialize_posthog_context(
    request: Request, call_next: Callable[[Request], Awaitable[Response]]
):
    user_id = get_current_user_safe(request)
    with posthog.new_context():
        if user_id is not None:
            posthog.identify_context(user_id)
        return await call_next(request)

Expected Result

It should pick up the distinct_id that is setup in middleware

Actual Result

It doesn't pick up distinct_id from the middleware

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions