Implement Feature Flags in Your Application
What you will build
Section titled “What you will build”By the end of this tutorial, you will have:
- The Optimizely SDK integrated in your application
- A feature flag that controls a new feature’s visibility
- Targeting rules that show the feature to specific users
- An experiment measuring whether the feature improves outcomes
Before you start
Section titled “Before you start”Ensure you have:
- Feature Experimentation access — Log into app.optimizely.com
- Your SDK key — Found in Settings → Environments in the Optimizely app
- A running application — This tutorial shows code for JavaScript/Node.js, C#, and Python
Step 1: Install the SDK
Section titled “Step 1: Install the SDK”npm install @optimizely/optimizely-sdk dotnet add package Optimizely.SDK pip install optimizely-sdk Step 2: Initialize the SDK
Section titled “Step 2: Initialize the SDK”The SDK needs your SDK key to download your project configuration.
import { createInstance } from '@optimizely/optimizely-sdk';
const optimizely = createInstance({
sdkKey: 'YOUR_SDK_KEY',
});
// Wait for the SDK to be ready
await optimizely.onReady();
console.log('Optimizely SDK initialized'); using OptimizelySDK;
var optimizely = OptimizelyFactory.NewDefaultInstance(
"YOUR_SDK_KEY"
);
// SDK is ready when NewDefaultInstance returns
Console.WriteLine("Optimizely SDK initialized"); from optimizely import optimizely
client = optimizely.Optimizely(sdk_key='YOUR_SDK_KEY')
# SDK downloads config automatically
print('Optimizely SDK initialized') Replace YOUR_SDK_KEY with the key from your Optimizely project settings.
Step 3: Create a feature flag in the Optimizely app
Section titled “Step 3: Create a feature flag in the Optimizely app”- Log into app.optimizely.com
- Navigate to Features → Feature Flags
- Click “Create New Feature”
- Set the key to
new_dashboard(this is what you will reference in code) - Add a variable:
- Key:
welcome_message - Type: String
- Default value:
"Welcome to your dashboard"
- Key:
- Click “Save”
Step 4: Check the feature flag in code
Section titled “Step 4: Check the feature flag in code”Now add the feature flag check to your application code. This is the core pattern you will use everywhere.
// Create a user context with attributes
const user = optimizely.createUserContext('user-123', {
plan: 'enterprise',
country: 'US',
});
// Decide whether to show the new dashboard
const decision = user.decide('new_dashboard');
if (decision.enabled) {
const welcomeMessage = decision.variables.welcome_message;
console.log(`Showing new dashboard: ${welcomeMessage}`);
renderNewDashboard(welcomeMessage);
} else {
console.log('Showing current dashboard');
renderCurrentDashboard();
} // Create a user context with attributes
var user = optimizely.CreateUserContext("user-123",
new UserAttributes
{
{ "plan", "enterprise" },
{ "country", "US" },
});
// Decide whether to show the new dashboard
var decision = user.Decide("new_dashboard");
if (decision.Enabled)
{
var welcomeMessage = decision.Variables["welcome_message"];
Console.WriteLine($"Showing new dashboard: {welcomeMessage}");
RenderNewDashboard(welcomeMessage.ToString());
}
else
{
Console.WriteLine("Showing current dashboard");
RenderCurrentDashboard();
} # Create a user context with attributes
user = client.create_user_context('user-123', {
'plan': 'enterprise',
'country': 'US',
})
# Decide whether to show the new dashboard
decision = user.decide('new_dashboard')
if decision.enabled:
welcome_message = decision.variables['welcome_message']
print(f'Showing new dashboard: {welcome_message}')
render_new_dashboard(welcome_message)
else:
print('Showing current dashboard')
render_current_dashboard() Key points:
createUserContextidentifies the user and passes attributes for targetingdecidereturns whether the feature is enabled and any variable values- User attributes (
plan,country) are used by targeting rules — set attributes that are relevant to your audience definitions
Step 5: Create a targeted rollout
Section titled “Step 5: Create a targeted rollout”Now control who sees the feature using the Optimizely app.
- Go to your
new_dashboardfeature flag - Click “Add Rule” → “Targeted Delivery”
- Set the audience:
plan is "enterprise" - Set traffic to 10% (start small)
- Click “Save” and then “Publish”
Now only 10% of enterprise users see the new dashboard. Everyone else sees the current dashboard.
Step 6: Track events
Section titled “Step 6: Track events”To measure the impact of your feature, track user actions.
// When the user completes a key action
user.trackEvent('dashboard_task_completed');
// Track with revenue (in cents)
user.trackEvent('purchase', { revenue: 4999 }); // When the user completes a key action
user.TrackEvent("dashboard_task_completed");
// Track with revenue (in cents)
user.TrackEvent("purchase",
new EventTags {{ "revenue", 4999 }}); # When the user completes a key action
user.track_event('dashboard_task_completed')
# Track with revenue (in cents)
user.track_event('purchase', event_tags={'revenue': 4999}) Create the event in the Optimizely app first: Events → Create New Event → key: dashboard_task_completed.
Step 7: Run an experiment
Section titled “Step 7: Run an experiment”Now turn your feature flag into an experiment to measure its impact.
- Go to your
new_dashboardfeature flag - Click “Add Rule” → “A/B Test”
- Set variations:
- Control: Feature OFF (current dashboard)
- Treatment: Feature ON (new dashboard)
- Add your primary metric:
dashboard_task_completed - Set traffic allocation to 50/50
- Target audience:
plan is "enterprise" - Click “Start Experiment”
Step 8: Increase rollout gradually
Section titled “Step 8: Increase rollout gradually”As the experiment collects data and you gain confidence:
- Check results in Reports — wait for statistical significance
- If winning, increase traffic: 10% → 25% → 50% → 100%
- Monitor error rates and performance at each stage
- When at 100% with stable metrics, the feature is fully released
Step 9: Use the kill switch
Section titled “Step 9: Use the kill switch”If something goes wrong at any stage:
- Go to your feature flag
- Turn it OFF or reduce traffic to 0%
- Click “Publish”
- The feature is instantly hidden — no code deploy needed
This is the power of feature flags: instant rollback without touching your deployment pipeline.
Step 10: Clean up
Section titled “Step 10: Clean up”Once the feature is permanently rolled out:
- Remove the feature flag check from your code
- Delete the feature flag in the Optimizely app
- Remove the old code path (the
elsebranch)
Do not leave stale feature flags in your codebase. They accumulate as technical debt.
What to do next
Section titled “What to do next”- Add more flags — Every new feature should ship behind a flag
- Explore targeting — Use attributes like
country,user_tier,signup_date - Try mutual exclusion — Run multiple experiments without interference
- Connect to ODP — Target experiments to rich behavioral segments