Skip to content

Add request-scoped context and web middleware helpers #151

Description

@marandaneto

Summary

Add request-scoped identity/context support to the Rust SDK, plus middleware/tracing-header helpers for common Rust web frameworks.

Motivation

Python has contexts (new_context, identify_context, set_context_session, tag) and Django middleware that can apply identity/session metadata to all events captured during a request. Go has request-context helpers and middleware. Rust currently requires callers to pass distinct_id, $session_id, and shared properties manually for each capture, exception, and feature flag evaluation.

This makes it harder to connect backend Rust events/errors/flag evaluations to frontend sessions and replays, especially when using PostHog JS tracing headers:

  • X-PostHog-Distinct-Id
  • X-PostHog-Session-Id

Proposed scope

Provide a Rust-native way to set request-scoped PostHog context and framework integrations that populate it from incoming requests.

Possible API shape:

let ctx = PostHogContext::new()
    .distinct_id("user_123")
    .session_id("session_uuid")
    .property("request_id", request_id)?;

client.capture_with_context(ctx.clone(), event).await?;
let flags = client.evaluate_flags_with_context(ctx.clone(), options).await?;
client.capture_exception_with_context(&error, ctx).await?;

Or, if there's a more idiomatic Rust approach, use task-local/request-extension state and helpers.

Middleware candidates:

  • tower/axum first, since this covers a broad set of Rust web apps.
  • Actix support can be part of this issue or a follow-up depending on implementation size.

Middleware should be able to:

  • Extract X-PostHog-Distinct-Id and X-PostHog-Session-Id from incoming requests.
  • Attach request-scoped defaults for captures and exceptions.
  • Make the request-scoped distinct ID available for feature flag evaluation.
  • Allow an authenticated server-side distinct ID to override client-controlled tracing headers for security-sensitive events/decisions.

Acceptance criteria

  • Rust SDK has a request-scoped context API for distinct ID, session ID, and shared properties/tags.
  • Captures, exceptions, and feature flag evaluations can consume this context.
  • At least one middleware integration (preferably tower/axum) extracts PostHog tracing headers and populates context.
  • Docs clearly warn that tracing headers are client-controlled analytics context, not authentication/authorization.
  • Tests cover context propagation and header extraction.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions