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§
- Async
Flag Poller - Asynchronous poller for feature flag definitions.
- Before
Send Hook - Hook that can modify or discard events before they are sent.
- Capture
Exception Options - Optional context for
capture_exception_with: person identity, custom properties, groups, and exception fingerprint/level. - Capture
Failure - Details of a terminal capture batch failure.
- Capture
Summary - 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 anErrinstead). - Client
- A
Clientfacilitates interactions with the PostHog API over HTTP. - Client
Options - Configuration options for the PostHog client.
- Client
Options Builder - Builder for
ClientOptions. - Cohort
- A cohort definition for local evaluation.
- Cohort
Definition - Definition of a cohort for local evaluation
- Endpoint
Manager - Manages PostHog API endpoints and host configuration.
- Error
Tracking Options - Client-level Error Tracking configuration, applied to every exception the
client captures. Set it via
ErrorTrackingOptionsBuilderonClientOptions::error_tracking. - Error
Tracking Options Builder - Builder for
ErrorTrackingOptions. - Evaluate
Flags Options - Optional inputs for
Client::evaluate_flags. - Evaluation
Context - Context for evaluating properties that may depend on cohorts or other flags.
- Event
- An
Eventrepresents 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. - Feature
Flag - A feature flag definition from PostHog.
- Feature
Flag Condition - A single condition group within a feature flag’s targeting rules.
- Feature
Flag Evaluations - A snapshot of evaluated feature flags for one
distinct_id. - Feature
Flag Filters - Targeting rules and configuration for a feature flag.
- Flag
Cache - Thread-safe cache for feature flag definitions.
- Flag
Detail - Detailed information about a feature flag evaluation result.
- Flag
Metadata - Metadata about a feature flag from the PostHog server.
- Flag
Poller - Synchronous poller for feature flag definitions.
- Flag
Reason - Explains why a feature flag evaluated to a particular value.
- Flags
Failure - Details of a failed remote
/flagsrequest. - Inconclusive
Match Error - Error returned when a feature flag cannot be evaluated locally.
- Local
Evaluation Config - Configuration for local flag evaluation.
- Local
Evaluation Failure - Details of a failed local-evaluation definitions poll.
- Local
Evaluation Response - Response from the PostHog local evaluation API.
- Local
Evaluator - Evaluates feature flags using locally cached definitions.
- Multivariate
Filter - Configuration for multivariate (A/B/n) feature flags.
- Multivariate
Variant - A single variant in a multivariate feature flag.
- Property
- A property filter used in feature flag targeting.
Enums§
- Capture
Compression - Request-body compression algorithm for the capture pipelines.
- Client
Options Builder Error - Error type for ClientOptionsBuilder
- Endpoint
- API endpoints used by the SDK for different operations.
- Error
- Errors that can occur when using the PostHog client.
- Error
Tracking Options Builder Error - Error type for ErrorTrackingOptionsBuilder
- Feature
Flags Response - Response from the PostHog feature flags API.
- Flag
Value - The value of a feature flag evaluation.
- Post
HogError - A terminal failure on one of the SDK’s network surfaces, passed by reference
to each registered
on_errorhook.
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_globalhas not run. - global_
is_ disabled - Return
trueif 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_globalhas not run.