Server Secret Keys should always be kept private. If you expose one, you can disable and recreate it in the Statsig console.
There is also an optional parameter named options that allows you to pass in a StatsigOptions to customize the SDK.
Copy
Ask AI
use statsig_rust::{Statsig, StatsigOptions};use std::sync::Arc;// Simple initializationlet statsig = Statsig::new("server-secret-key", None);statsig.initialize().await?;// Or with StatsigOptionslet mut options = StatsigOptions::default();options.environment = Some("development".to_string());let statsig = Statsig::new("server-secret-key", Some(Arc::new(options)));statsig.initialize().await?;// Don't forget to shutdown when donestatsig.shutdown().await?;
initialize will perform a network request. After initialize completes, virtually all SDK operations will be synchronous (See Evaluating Feature Gates in the Statsig SDK). The SDK will fetch updates from Statsig in the background, independently of your API calls.
Now that your SDK is initialized, let’s fetch a Feature Gate. Feature Gates can be used to create logic branches in code that can be rolled out to different users from the Statsig Console. Gates are always CLOSED or OFF (think return false;) by default.From this point on, all APIs will require you to specify the user (see Statsig user) associated with the request. For example, check a gate for a certain user like this:
Copy
Ask AI
use statsig_rust::{Statsig, StatsigUserBuilder};let user = StatsigUserBuilder::new_with_user_id("a-user".to_string()).build();if statsig.check_gate(&user, "a_gate") { // Gate is on, enable new feature} else { // Gate is off}
Feature Gates can be very useful for simple on/off switches, with optional but advanced user targeting. However, if you want to be send a different set of values (strings, numbers, and etc.) to your clients based on specific user attributes, e.g. country, Dynamic Configs can help you with that. The API is very similar to Feature Gates, but you get an entire json object you can configure on the server and you can fetch typed parameters from it. For example:
Copy
Ask AI
use statsig_rust::{Statsig, StatsigUserBuilder, DynamicConfigEvaluationOptions};use std::sync::Arc;// Get a dynamic config for a specific userlet user = StatsigUserBuilder::new_with_user_id("my_user".to_string()).build();let config = statsig.get_dynamic_config(&user, "a_config");// Access config values with type-safe getters and fallback valueslet product_name = config.get_string("product_name", "Awesome Product v1"); // returns Stringlet price = config.get_double("price", 10.0); // returns f64let should_discount = config.get_bool("discount", false); // returns boollet quantity = config.get_int("quantity", 1); // returns i64// Advanced Usage:// You can disable exposure logging for this specific checklet mut options = DynamicConfigEvaluationOptions::default();options.disable_exposure_logging = Some(true);let config = statsig.get_dynamic_config_with_options(&user, "a_config", &options);// The config object also provides metadata about the evaluationprintln!("{}", config.rule_id); // The ID of the rule that served this configprintln!("{}", config.id_type); // The type of the evaluation (experiment, config, etc)
Then we have Layers/Experiments, which you can use to run A/B/n experiments. We offer two APIs, but often recommend the use of layers, which make parameters reusable and let you run mutually exclusive experiments.
Copy
Ask AI
use statsig_rust::{Statsig, StatsigUserBuilder};// Values via get_layerlet user = StatsigUserBuilder::new_with_user_id("my_user".to_string()).build();let layer = statsig.get_layer(&user, "user_promo_experiments");let title = layer.get_string("title", "Welcome to Statsig!");let discount = layer.get_double("discount", 0.1);// Via get_experimentlet title_exp = statsig.get_experiment(&user, "new_user_promo_title");let price_exp = statsig.get_experiment(&user, "new_user_promo_price");let title = title_exp.get_string("title", "Welcome to Statsig!");let discount = price_exp.get_double("discount", 0.1);
Sometimes you don’t know whether you want a value to be a Feature Gate, Experiment, or Dynamic Config yet. If you want on-the-fly control of that outside of your deployment cycle, you can use Parameter Stores to define a parameter that can be changed into at any point in the Statsig console. Parameter Stores are optional, but parameterizing your application can prove very useful for future flexibility and can even allow non-technical Statsig users to turn parameters into experiments.
Copy
Ask AI
let param_store = statsig.get_parameter_store("my_parameters");let param_store_value = param_store.get(&user, "my_parameter_value", false); //false is fallback valueprintln!("param_store_value: {}", param_store_value);
Now that you have a Feature Gate or an Experiment set up, you may want to track some custom events and see how your new features or different experiment groups affect these events. This is super easy with Statsig—simply call the Log Event API and specify the user and event name to log; you additionally provide some value and/or an object of metadata to be logged together with the event:
Copy
Ask AI
use statsig_rust::{Statsig, StatsigUserBuilder};use std::collections::HashMap;use crate::evaluation::dynamic_value::DynamicValue;// Create a userlet user = StatsigUserBuilder::new_with_user_id("user_id".to_string()).build();// Create metadata hashmaplet mut metadata = HashMap::new();metadata.insert("price".to_string(), "9.99".into());metadata.insert("item_name".to_string(), "diet_coke_48_pack".into());// Log the eventstatsig.log_event( &user, "add_to_cart", Some("SKU_12345".into()), // value as DynamicValue Some(metadata));
Learn more about identifying users, group analytics, and best practices for logging events in the logging events guide.
In certain scenarios, you may need more information about a gate evaluation than just a boolean value. For additional metadata about the evaluation, use the Get Feature Gate API, which returns a FeatureGate object:
Copy
Ask AI
use statsig_rust::{Statsig, StatsigUserBuilder};// Create a userlet user = StatsigUserBuilder::new_with_user_id("user_id".to_string()).build();// Get a feature gatelet gate = statsig.get_feature_gate(&user, "example_gate");// Access gate propertiesprintln!("{}", gate.rule_id);println!("{}", gate.value); // Boolean value of the gate
In some applications, you may want to create a single Statsig instance that can be accessed globally throughout your codebase. The shared instance functionality provides a singleton pattern for this purpose:
Copy
Ask AI
// Create a shared instance that can be accessed globallylet statsig = Statsig::new_shared("server-secret-key", None).unwrap();statsig.initialize().await?;// Access the shared instance from anywhere in your codelet shared_statsig = Statsig::shared();let is_feature_enabled = shared_statsig.check_gate(&user, "feature_name");// Check if a shared instance existsif Statsig::has_shared_instance() { // Use the shared instance}// Remove the shared instance when no longer neededStatsig::remove_shared();
The shared instance functionality provides a singleton pattern where a single Statsig instance can be created and accessed globally throughout your application. This is useful for applications that need to access Statsig functionality from multiple parts of the codebase without having to pass around a Statsig instance.
Statsig::new_shared(sdk_key, options): Creates a new shared instance of Statsig that can be accessed globally
Statsig::shared(): Returns the shared instance
Statsig::has_shared_instance(): Checks if a shared instance exists (useful when you aren’t sure if the shared instance is ready yet)
Statsig::remove_shared(): Removes the shared instance (useful when you want to switch to a new shared instance)
has_shared_instance() and remove_shared() are helpful in specific scenarios but aren’t required in most use cases where the shared instance is set up near the top of your application.Also note that only one shared instance can exist at a time. Attempting to create a second shared instance will result in an error.
By default, the SDK will automatically log an exposure event when you check a gate, get a config, get an experiment, or get a layer. However, there are times when you may want to log an exposure event manually. For example, if you’re using a gate to control access to a feature, but you don’t want to log an exposure until the user actually uses the feature, you can use manual exposures.All of the main SDK functions (check_gate, get_dynamic_config, get_experiment, get_layer) accept an options parameter with a disable_exposure_logging field. When this is set to true, the SDK will not automatically log an exposure event. You can then manually log the exposure at a later time using the corresponding manual exposure logging method:
Feature Gates
Dynamic Configs
Experiments
Layers
Copy
Ask AI
result = statsig.check_gate_with_options(&user, 'a_gate_name', FeatureGateEvaluationOptions {disable_exposure_logging: true});
The StatsigUser object represents a user in Statsig. You must provide a userID or at least one of the customIDs to identify the user.When calling APIs that require a user, you should pass as much information as possible in order to take advantage of advanced gate and config conditions (like country or OS/browser level checks), and correctly measure impact of your experiments on your metrics/events. At least one ID (userID or customID) is required because it’s needed to provide a consistent experience for a given user (click here)Besides userID, we also have email, ip, userAgent, country, locale and appVersion as top-level fields on StatsigUser. In addition, you can pass any key-value pairs in an object/dictionary to the custom field and be able to create targeting based on them.
Private attributes are user attributes that are used for evaluation but are not forwarded to any integrations. They are useful for PII or sensitive data that you don’t want to send to third-party services.
Copy
Ask AI
use statsig_rust::StatsigUserBuilder;use std::collections::HashMap;// Create a user with just a user IDlet user = StatsigUserBuilder::new_with_user_id("user-123".to_string()) .build();// Or create a user with custom IDslet mut custom_ids = HashMap::new();custom_ids.insert("employee_id".to_string(), "emp-456".to_string());let user_with_custom_ids = StatsigUserBuilder::new_with_custom_ids(custom_ids) .build();// Create a user with several propertieslet mut custom_fields = HashMap::new();custom_fields.insert("plan".to_string(), "premium".into());custom_fields.insert("age".to_string(), 25.into());let user = StatsigUserBuilder::new_with_user_id("user-123".to_string()) .email(Some("user@example.com".to_string())) .ip(Some("192.168.1.1".to_string())) .user_agent(Some("Mozilla/5.0...".to_string())) .country(Some("US".to_string())) .locale(Some("en-US".to_string())) .app_version(Some("1.0.0".to_string())) .custom(Some(custom_fields)) .build();// Private Attributes (not forwarded to integrations)let mut private_attrs = HashMap::new();private_attrs.insert("internal_id".to_string(), "emp-123".into());let user_with_private = StatsigUserBuilder::new_with_user_id("user-123".to_string()) .email(Some("user@example.com".to_string())) .private_attributes(Some(private_attrs)) .build();
You can pass in an optional parameter options in addition to sdkKey during initialization to customize the Statsig client. Here are the available options that you can configure.
If set to true, the SDK will NOT attempt to parse UserAgents (attached to the user object) into browserName, browserVersion, systemName, systemVersion, and appVersion at evaluation time, when needed for evaluation.
When set to true, the SDK will wait until user agent parsing data is fully loaded during initialization. This may slow down by ~1 second startup but ensures that parsing of the user’s userAgent string into fields like browserName, browserVersion, systemName, systemVersion, and appVersion is ready before any evaluations.
If set to true, the SDK will NOT attempt to parse IP addresses (attached to the user object at user.ip) into Country codes at evaluation time, when needed for evaluation.
When set to true, the SDK will wait for country lookup data (e.g., GeoIP or YAML files) to fully load during initialization. This may slow down by ~1 second startup but ensures that IP-to-country parsing is ready at evaluation time.
Because we batch and periodically flush events, some events may not have been sent when your app/server shuts down. To make sure all logged events are properly flushed, you should call shutdown() before your app/server shuts down:
Copy
Ask AI
statsig.shutdown().await?;
Alternatively, you can manually flush events without shutting down:
Copy
Ask AI
// Manually flush events to the serverstatsig.flush_events().await;
The Statsig SDK provides an event subscription system that allows you to listen for evaluation events in real-time. This feature is useful for debugging, analytics, custom logging, and integrating with external systems.
Local Overrides are a way to override the values of gates, configs, experiments, and layers for testing purposes. This is useful for local development or testing scenarios where you want to force a specific value without having to change the configuration in the Statsig console.
Copy
Ask AI
// Overrides the given gate to the specified valuestatsig.override_gate("test_gate", true, None);// Overrides the given dynamic config to the provided valuestatsig.override_dynamic_config("test_1", my_map.clone(), None); //my_map is HashMap<String, Value>// Overrides the given experiment to the provided valuestatsig.override_experiment("test_xp_1", my_map.clone(), None); //my_map is HashMap<String, Value>// Overrides the given layer to the provided valuestatsig.override_layer("user_promo_experiments", my_map.clone(), None); //my_map is HashMap<String, Value>//Alternatively, get the Experiment object for a given groupNamelet group_exp = statsig.get_experiment_by_group_name("pricing_experiment", "premium_group");let premium_price = group_exp.get_double("price", 9.99);
The Persistent Storage interface allows you to implement custom storage for user-specific configurations. This enables you to persist user assignments across sessions, ensuring consistent experiment groups even when the user returns later. This is particularly useful for client-side A/B testing where you want to ensure users always see the same variant.
The Data Store interface allows you to implement custom storage for Statsig configurations. This enables advanced caching strategies and integration with your preferred storage systems.
The Output Logger interface allows you to customize how the SDK logs messages. This enables integration with your own logging system and control over log verbosity.
The Observability Client interface allows you to monitor the health of the SDK by integrating with your own observability systems. This enables tracking metrics, errors, and performance data. For more information on the metrics emitted by Statsig SDKs, see the Monitoring documentation.
This is available for Enterprise contracts. Please reach out to our support team, your sales contact, or via our slack channel if you want this enabled.
These methods allow you to retrieve a list of user fields that are used in the targeting rules for gates, configs, experiments, and layers.
These methods return an array of strings representing the user fields that are referenced in the targeting rules or conditions of the specified feature. This can be useful for understanding which user properties influence a particular feature’s behavior.
Copy
Ask AI
// Get fields needed for a gatelet fields_needed: Vec<String> = statsig.get_fields_needed_for_gate("gate_name");// Get fields needed for a dynamic configlet fields_needed: Vec<String> = statsig.get_fields_needed_for_dynamic_config("config_name");// Get fields needed for an experimentlet fields_needed: Vec<String> = statsig.get_fields_needed_for_experiment("experiment_name");// Get fields needed for a layerlet fields_needed: Vec<String> = statsig.get_fields_needed_for_layer("layer_name");
// Get user fields needed for a gate evaluationpub fn get_fields_needed_for_gate(&self, gate_name: &str) -> Vec<String>// Get user fields needed for a dynamic config evaluationpub fn get_fields_needed_for_dynamic_config(&self, config_name: &str) -> Vec<String>// Get user fields needed for an experiment evaluationpub fn get_fields_needed_for_experiment(&self, experiment_name: &str) -> Vec<String>// Get user fields needed for a layer evaluationpub fn get_fields_needed_for_layer(&self, layer_name: &str) -> Vec<String>
This is available for Enterprise contracts. Please reach out to our support team, your sales contact, or via our slack channel if you want this enabled.
These methods allow you to retrieve a list of user fields that are used in the targeting rules for gates, configs, experiments, and layers.
These methods return an array of strings representing the user fields that are referenced in the targeting rules or conditions of the specified feature. This can be useful for understanding which user properties influence a particular feature’s behavior.