Skip to content

Implement Feature Flags in Your Application

⏱ 45 minutes beginner
📜Foundationexperimentation

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

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
Install the Optimizely SDK
bash
npm install @optimizely/optimizely-sdk
bash
dotnet add package Optimizely.SDK
bash
pip install optimizely-sdk

The SDK needs your SDK key to download your project configuration.

Initialize the SDK
javascript
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');
csharp
using OptimizelySDK;

var optimizely = OptimizelyFactory.NewDefaultInstance(
    "YOUR_SDK_KEY"
);

// SDK is ready when NewDefaultInstance returns
Console.WriteLine("Optimizely SDK initialized");
python
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”
  1. Log into app.optimizely.com
  2. Navigate to Features → Feature Flags
  3. Click “Create New Feature”
  4. Set the key to new_dashboard (this is what you will reference in code)
  5. Add a variable:
    • Key: welcome_message
    • Type: String
    • Default value: "Welcome to your dashboard"
  6. Click “Save”

Now add the feature flag check to your application code. This is the core pattern you will use everywhere.

Check if a feature is enabled
javascript
// 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();
}
csharp
// 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();
}
python
# 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:

  • createUserContext identifies the user and passes attributes for targeting
  • decide returns 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

Now control who sees the feature using the Optimizely app.

  1. Go to your new_dashboard feature flag
  2. Click “Add Rule” → “Targeted Delivery”
  3. Set the audience: plan is "enterprise"
  4. Set traffic to 10% (start small)
  5. Click “Save” and then “Publish”

Now only 10% of enterprise users see the new dashboard. Everyone else sees the current dashboard.

To measure the impact of your feature, track user actions.

Track a conversion event
javascript
// When the user completes a key action
user.trackEvent('dashboard_task_completed');

// Track with revenue (in cents)
user.trackEvent('purchase', { revenue: 4999 });
csharp
// When the user completes a key action
user.TrackEvent("dashboard_task_completed");

// Track with revenue (in cents)
user.TrackEvent("purchase",
    new EventTags {{ "revenue", 4999 }});
python
# 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.

Now turn your feature flag into an experiment to measure its impact.

  1. Go to your new_dashboard feature flag
  2. Click “Add Rule” → “A/B Test”
  3. Set variations:
    • Control: Feature OFF (current dashboard)
    • Treatment: Feature ON (new dashboard)
  4. Add your primary metric: dashboard_task_completed
  5. Set traffic allocation to 50/50
  6. Target audience: plan is "enterprise"
  7. Click “Start Experiment”

As the experiment collects data and you gain confidence:

  1. Check results in Reports — wait for statistical significance
  2. If winning, increase traffic: 10% → 25% → 50% → 100%
  3. Monitor error rates and performance at each stage
  4. When at 100% with stable metrics, the feature is fully released

If something goes wrong at any stage:

  1. Go to your feature flag
  2. Turn it OFF or reduce traffic to 0%
  3. Click “Publish”
  4. The feature is instantly hidden — no code deploy needed

This is the power of feature flags: instant rollback without touching your deployment pipeline.

Once the feature is permanently rolled out:

  1. Remove the feature flag check from your code
  2. Delete the feature flag in the Optimizely app
  3. Remove the old code path (the else branch)

Do not leave stale feature flags in your codebase. They accumulate as technical debt.

  • 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