Skip to main content

Crate posthog_rs

Crate posthog_rs 

Source
Expand description

Official Rust SDK for PostHog.

Use client to construct a Client, Event to capture analytics events, and Client::evaluate_flags with EvaluateFlagsOptions for feature flag evaluation.

See the PostHog Rust SDK documentation for installation, configuration, and more examples.

§Getting started

Add posthog-rs to your Cargo.toml, then initialize a client with your project API key.

use posthog_rs::{client, EvaluateFlagsOptions, Event};

#[cfg(feature = "async-client")]
#[tokio::main]
async fn main() -> Result<(), posthog_rs::Error> {
    let api_key = std::env::var("POSTHOG_API_KEY")
        .expect("set POSTHOG_API_KEY to your PostHog project API key");

    let posthog = client(api_key.as_str()).await;
    let distinct_id = "user-123";

    // Capture an analytics event.
    let mut event = Event::new("signed_up", distinct_id);
    event.insert_prop("plan", "pro")?;
    posthog.capture(event);

    // Evaluate feature flags once, then read from the snapshot.
    let flags = posthog
        .evaluate_flags(distinct_id, EvaluateFlagsOptions::default())
        .await?;

    if flags.is_enabled("new-onboarding") {
        let mut event = Event::new("onboarding_step_completed", distinct_id);
        event.with_flags(&flags.only_accessed());
        posthog.capture(event);
    }

    Ok(())
}

#[cfg(not(feature = "async-client"))]
fn main() -> Result<(), posthog_rs::Error> {
    let api_key = std::env::var("POSTHOG_API_KEY")
        .expect("set POSTHOG_API_KEY to your PostHog project API key");

    let posthog = client(api_key.as_str());
    let distinct_id = "user-123";

    // Capture an analytics event.
    let mut event = Event::new("signed_up", distinct_id);
    event.insert_prop("plan", "pro")?;
    posthog.capture(event);

    // Evaluate feature flags once, then read from the snapshot.
    let flags = posthog.evaluate_flags(distinct_id, EvaluateFlagsOptions::default())?;

    if flags.is_enabled("new-onboarding") {
        let mut event = Event::new("onboarding_step_completed", distinct_id);
        event.with_flags(&flags.only_accessed());
        posthog.capture(event);
    }

    Ok(())
}

§Capture is fire-and-forget

Client::capture and Client::capture_batch are the primary API: they hand the event to a background worker that batches, sends, and retries it, and return immediately. Delivery failures are not surfaced to the caller — register ClientOptionsBuilder::on_error to observe them. This is the right choice for essentially all analytics.

§Immediate delivery (advanced)

Client::capture_immediate and Client::capture_batch_immediate send inline and return a CaptureSummary once the request reaches a terminal outcome (or an Error if the retry budget is spent). They bypass the background worker and do not fire on_error — the returned value is the signal. Reach for them only when the caller must know a batch persisted before advancing its own durable state (for example, a server-side importer committing an upstream offset); prefer fire-and-forget everywhere else.

Structs§

AsyncFlagPoller
Asynchronous poller for feature flag definitions.
BeforeSendHook
Hook that can modify or discard events before they are sent.
CaptureExceptionOptions
Optional context for capture_exception_with: person identity, custom properties, groups, and exception fingerprint/level.
CaptureFailure
Details of a terminal capture batch failure.
CaptureSummary
The outcome of an immediate capture (Client::capture_immediate / Client::capture_batch_immediate), returned once the SDK has a terminal result for the batch — the request succeeded, or the retry budget was spent (which is an Err instead).
Client
A Client facilitates interactions with the PostHog API over HTTP.
ClientOptions
Configuration options for the PostHog client.
ClientOptionsBuilder
Builder for ClientOptions.
Cohort
A cohort definition for local evaluation.
CohortDefinition
Definition of a cohort for local evaluation
EndpointManager
Manages PostHog API endpoints and host configuration.
ErrorTrackingOptions
Client-level Error Tracking configuration, applied to every exception the client captures. Set it via ErrorTrackingOptionsBuilder on ClientOptions::error_tracking.
ErrorTrackingOptionsBuilder
Builder for ErrorTrackingOptions.
EvaluateFlagsOptions
Optional inputs for Client::evaluate_flags.
EvaluationContext
Context for evaluating properties that may depend on cohorts or other flags.
Event
An Event represents an interaction a user has with your app or website. Examples include button clicks, pageviews, query completions, and signups. See the PostHog documentation for a detailed explanation of PostHog Events.
FeatureFlag
A feature flag definition from PostHog.
FeatureFlagCondition
A single condition group within a feature flag’s targeting rules.
FeatureFlagEvaluations
A snapshot of evaluated feature flags for one distinct_id.
FeatureFlagFilters
Targeting rules and configuration for a feature flag.
FlagCache
Thread-safe cache for feature flag definitions.
FlagDetail
Detailed information about a feature flag evaluation result.
FlagMetadata
Metadata about a feature flag from the PostHog server.
FlagPoller
Synchronous poller for feature flag definitions.
FlagReason
Explains why a feature flag evaluated to a particular value.
FlagsFailure
Details of a failed remote /flags request.
InconclusiveMatchError
Error returned when a feature flag cannot be evaluated locally.
LocalEvaluationConfig
Configuration for local flag evaluation.
LocalEvaluationFailure
Details of a failed local-evaluation definitions poll.
LocalEvaluationResponse
Response from the PostHog local evaluation API.
LocalEvaluator
Evaluates feature flags using locally cached definitions.
MultivariateFilter
Configuration for multivariate (A/B/n) feature flags.
MultivariateVariant
A single variant in a multivariate feature flag.
Property
A property filter used in feature flag targeting.

Enums§

CaptureCompression
Request-body compression algorithm for the capture pipelines.
ClientOptionsBuilderError
Error type for ClientOptionsBuilder
Endpoint
API endpoints used by the SDK for different operations.
Error
Errors that can occur when using the PostHog client.
ErrorTrackingOptionsBuilderError
Error type for ErrorTrackingOptionsBuilder
FeatureFlagsResponse
Response from the PostHog feature flags API.
FlagValue
The value of a feature flag evaluation.
PostHogError
A terminal failure on one of the SDK’s network surfaces, passed by reference to each registered on_error hook.

Constants§

DEFAULT_HOST
Default host (US by default)
EU_INGESTION_ENDPOINT
EU ingestion endpoint
US_INGESTION_ENDPOINT
US ingestion endpoint

Functions§

capture
Capture the provided event using the global client.
capture_exception
Capture a Rust error personlessly using the global client.
capture_exception_with
Capture a Rust error with optional context using the global client.
client
Construct an async PostHog client from an API key or ClientOptions.
disable_global
Prevent the global client from being initialized.
flush
Flush the global client’s queued events, awaiting the worker’s next delivery attempt. No-op if init_global has not run.
global_is_disabled
Return true if global client initialization has been disabled.
init_global
Initialize the global client singleton.
match_feature_flag
Evaluate a feature flag definition against person and optional group context.
match_feature_flag_with_context
Match a feature flag with full context (cohorts, other flags).
match_property_with_context
Match a property with additional context for cohorts and flag dependencies.
shutdown
Flush and stop the global client’s background worker. Idempotent; no-op if init_global has not run.