Flagdeck
Pricing
Docs
Get Started

Docs

Docs


SDKs

  • JavaScript
    • Getting Started
    • Value Types
    • Evaluation Context
    • Configuration
    • Real Time Updates
    • Error Handling
    • Middleware
    • Offline Mode
    • API Reference
  • React

API Reference

  • Authentication
  • Flags
  • Environments
  • Projects

Real-Time Flag Updates

Flagdeck's real-time updates feature allows your application to instantly react to flag changes without requiring page refreshes or API polling. This powerful capability enables dynamic experiences and immediate application responses to configuration changes.

Overview

Real-time updates use Server-Sent Events (SSE) to establish a persistent connection between your application and Flagdeck servers. When flag changes occur in the Flagdeck dashboard, your application receives these changes instantly, allowing you to update your UI or application behavior in real-time.

Key Benefits

  • Instant Updates: Changes made in the Flagdeck dashboard are immediately reflected in your application
  • Reduced API Load: Eliminates the need for polling, reducing server load and API calls
  • Better User Experience: Features can be enabled/disabled without requiring users to refresh
  • Optimized Resource Usage: The SSE protocol is efficient and uses minimal bandwidth

Getting Started

Real-time updates are enabled by default in browser environments and disabled by default in server environments. You can control this behavior during SDK initialization:

// Enable real-time updates (default in browser environments)
const flagdeck = new Flagdeck({
  apiKey: 'your-api-key',
  realTimeUpdates: true
});

// Disable real-time updates
const flagdeck = new Flagdeck({
  apiKey: 'your-api-key',
  realTimeUpdates: false
});

Event Types

The Flagdeck SDK provides several event types you can listen for:

Flag Value Changes

Listen for changes to a specific flag's value:

flagdeck.onFlagChange('welcome-banner', (newValue, oldValue) => {
  console.log(`Welcome banner changed from ${oldValue} to ${newValue}`);

  if (newValue === true) {
    showWelcomeBanner();
  } else {
    hideWelcomeBanner();
  }
});

Flag Status Changes

Listen for when a flag is specifically enabled or disabled:

// When a flag is enabled
flagdeck.on('enabled:new-feature', (value) => {
  console.log('New feature was enabled!');
  showNewFeature();
});

// When a flag is disabled
flagdeck.on('disabled:new-feature', (value) => {
  console.log('New feature was disabled!');
  hideNewFeature();
});

Multiple Flag Changes

Listen for changes to any flags:

flagdeck.on('change', (changes) => {
  console.log('Multiple flags changed:', changes);
  // { flagKey1: { newValue, oldValue }, flagKey2: { newValue, oldValue } }

  // Update your application based on the changes
  if (changes['theme']) {
    applyTheme(changes['theme'].newValue);
  }

  if (changes['navigation']) {
    updateNavigation(changes['navigation'].newValue);
  }
});

Connection Events

Monitor the real-time connection status:

// Connection established
flagdeck.on('connected', () => {
  console.log('Connected to Flagdeck real-time updates');
  showConnectedIndicator();
});

// Connection lost
flagdeck.on('disconnected', (error) => {
  console.log('Disconnected from Flagdeck real-time updates', error);
  showDisconnectedIndicator();
});

// Connection error
flagdeck.on('error', (error) => {
  console.error('Real-time updates error', error);
  showErrorIndicator();
});

Managing Real-Time Updates at Runtime

You can enable or disable real-time updates during runtime:

Enable Real-Time Updates

// Basic usage
flagdeck.enableRealTimeUpdates();

// With options
flagdeck.enableRealTimeUpdates({
  // Automatically update cached values when flags change (default: true)
  autoUpdate: true,

  // Custom callback when a flag is updated
  onFlagUpdate: (flagKey, newValue) => {
    console.log(`Flag ${flagKey} updated to:`, newValue);
  },

  // Connection callbacks
  onConnect: () => {
    console.log('Connected to real-time updates');
  },
  onDisconnect: (error) => {
    console.log('Disconnected from real-time updates', error);
  }
});

Disable Real-Time Updates

// Disable real-time updates
flagdeck.disableRealTimeUpdates();

Check Real-Time Updates Status

// Check if real-time updates are enabled and connected
const enabled = flagdeck.areRealTimeUpdatesEnabled();
console.log('Real-time updates enabled:', enabled);

Reset Circuit Breaker

If connections are failing repeatedly, the SDK will engage a circuit breaker to prevent excessive reconnection attempts. You can manually reset this:

// Reset the circuit breaker to attempt reconnection
flagdeck.resetSseCircuitBreaker();

Server-Side Usage (Node.js)

In server environments, you'll typically want to be more selective about which flags you monitor to optimize resource usage:

// First enable real-time updates (disabled by default in Node.js)
flagdeck.enableRealTimeUpdates();

// Then subscribe to specific flags
flagdeck.subscribeToFlags(['payment-gateway', 'auth-method'], {
  priority: 'high',  // 'high', 'normal', or 'low'
  ttl: 3600000       // Subscription time-to-live in ms (1 hour)
});

Server-Side Considerations

When using real-time updates in Node.js:

  1. Install Required Package: For Node.js environments, you must install the eventsource package:
npm install eventsource
# or
yarn add eventsource
  1. Resource Usage: Be selective about which flags you subscribe to

  2. Connection Management: The SDK manages connections efficiently, but be mindful of the number of server instances connected to avoid overwhelming your network

Advanced Use Cases

Gradual Feature Rollout

Real-time updates enable smooth gradual rollouts without requiring users to refresh:

// Listen for changes to rollout percentage
flagdeck.onFlagChange('new-checkout', (newValue, oldValue) => {
  if (typeof newValue === 'object' && newValue?.rolloutPercentage !== undefined) {
    console.log(`Rollout percentage changed from ${oldValue?.rolloutPercentage || 0}% to ${newValue.rolloutPercentage}%`);

    // Update UI to reflect new rollout status
    updateRolloutIndicator(newValue.rolloutPercentage);
  }
});

A/B Testing

Dynamically switch between test variants:

flagdeck.onFlagChange('checkout-experiment', (newVariant, oldVariant) => {
  console.log(`Experiment variant changed from ${oldVariant} to ${newVariant}`);

  // Remove old variant UI
  if (oldVariant === 'A') {
    removeVariantA();
  } else if (oldVariant === 'B') {
    removeVariantB();
  }

  // Apply new variant UI
  if (newVariant === 'A') {
    applyVariantA();
  } else if (newVariant === 'B') {
    applyVariantB();
  }
});

Dynamic Configuration

Update application settings without requiring a restart:

flagdeck.onFlagChange('api-config', (newConfig, oldConfig) => {
  console.log('API configuration updated:', newConfig);

  // Update API client with new settings
  apiClient.updateConfig({
    baseUrl: newConfig.baseUrl,
    timeout: newConfig.timeout,
    retries: newConfig.retries
  });
});

Feature Announcements

Show announcements when new features are enabled:

flagdeck.on('enabled:new-analytics', (value) => {
  // Show an announcement toast
  showToast({
    title: 'New Feature Available!',
    message: 'Try our new analytics dashboard - now available in your account!',
    icon: 'chart-line',
    action: {
      label: 'Check it out',
      onClick: () => navigateTo('/analytics')
    }
  });
});

Implementation Details

Browser Implementation

In browser environments, the SDK uses the native EventSource API to establish SSE connections, with automatic reconnection logic.

Resource Management

The SDK intelligently manages resources:

  • Connection Sharing: A single SSE connection is shared across all flags to minimize resource usage
  • Automatic Cleanup: Unused flag subscriptions are cleaned up to free memory
  • Circuit Breaker Pattern: Prevents excessive reconnection attempts during outages
  • Exponential Backoff: Gradually increases delay between reconnection attempts

Connection State Recovery

If the connection is lost, the SDK will:

  1. Attempt to reconnect with exponential backoff
  2. Upon reconnection, synchronize flag states
  3. Emit appropriate events for any flags that changed while disconnected

Troubleshooting

Connection Issues

If you're experiencing connection issues:

  1. Check your network connectivity
  2. Verify your API key has proper permissions
  3. Check if there are any firewall or proxy issues blocking SSE connections
  4. Try resetting the circuit breaker: flagdeck.resetSseCircuitBreaker()
  5. Enable debug mode to see detailed logs: new Flagdeck({ debug: true, ... })

Delayed Updates

If updates seem delayed:

  1. Check your network latency to the Flagdeck servers
  2. Verify that caching is configured appropriately
  3. Ensure your event handlers are executing efficiently

Memory Usage Concerns

For long-running applications:

  1. Be selective about which flags you monitor
  2. Consider periodically disabling and re-enabling real-time updates
  3. In Node.js, use the ttl option when subscribing to flags

Best Practices

  1. Targeted Subscriptions: Subscribe only to flags your application actively uses
  2. Cleanup on Unmount: In component-based frameworks, disable real-time updates when components unmount
  3. Error Handling: Always include error handling in your event callbacks
  4. Fallback Mechanisms: Implement fallbacks for when real-time updates are unavailable
  5. Batched UI Updates: When handling multiple flag changes, batch UI updates for better performance

Example: Integration with React

import React, { useEffect, useState } from 'react';
import { Flagdeck } from '@flagdeck/js';

function FeatureFlag({ flagKey, children, fallback = null }) {
  const [isEnabled, setIsEnabled] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const flagdeck = new Flagdeck({
      apiKey: 'your-api-key',
      realTimeUpdates: true
    });

    // Initial check
    flagdeck.isEnabled(flagKey)
      .then(enabled => {
        setIsEnabled(enabled);
        setIsLoading(false);
      })
      .catch(error => {
        console.error(`Error checking flag ${flagKey}:`, error);
        setIsLoading(false);
      });

    // Listen for real-time updates
    flagdeck.onFlagChange(flagKey, (newValue) => {
      setIsEnabled(!!newValue);
    });

    // Cleanup on unmount
    return () => {
      flagdeck.off(`change:${flagKey}`);
      flagdeck.destroy();
    };
  }, [flagKey]);

  if (isLoading) {
    return <div>Loading...</div>;
  }

  return isEnabled ? children : fallback;
}

// Usage
function App() {
  return (
    <div>
      <h1>My App</h1>

      <FeatureFlag flagKey="new-dashboard" fallback={<LegacyDashboard />}>
        <NewDashboard />
      </FeatureFlag>
    </div>
  );
}

Example: Integration with Vue.js

// FeatureFlag.vue
<template>
  <slot v-if="isEnabled" />
  <slot v-else name="fallback" />
</template>

<script>
import { Flagdeck } from '@flagdeck/js';

export default {
  props: {
    flagKey: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      isEnabled: false,
      flagdeck: null
    };
  },
  async created() {
    this.flagdeck = new Flagdeck({
      apiKey: 'your-api-key',
      realTimeUpdates: true
    });

    // Initial check
    try {
      this.isEnabled = await this.flagdeck.isEnabled(this.flagKey);
    } catch (error) {
      console.error(`Error checking flag ${this.flagKey}:`, error);
    }

    // Listen for real-time updates
    this.flagdeck.onFlagChange(this.flagKey, (newValue) => {
      this.isEnabled = !!newValue;
    });
  },
  beforeDestroy() {
    if (this.flagdeck) {
      this.flagdeck.off(`change:${this.flagKey}`);
      this.flagdeck.destroy();
    }
  }
};
</script>

<!-- Usage -->
<template>
  <div>
    <h1>My App</h1>

    <feature-flag flag-key="new-dashboard">
      <new-dashboard />
      <template #fallback>
        <legacy-dashboard />
      </template>
    </feature-flag>
  </div>
</template>

Security Considerations

The real-time updates feature uses your SDK API key for authentication. To maintain security:

  1. Never expose your API key in client-side code for production environments
  2. Use environment-specific API keys with appropriate permissions
  3. Monitor your API key usage for unusual patterns
  4. Rotate API keys periodically according to your security policies

Summary

Real-time flag updates provide a powerful way to dynamically control your application's behavior without requiring users to refresh or restart. By following the patterns and best practices outlined in this guide, you can create responsive applications that adapt instantly to configuration changes made in the Flagdeck dashboard.

Start using Flagdeck today

Simple feature flag management for modern development teams.

Get Started
Flagdeck

Modern feature flag management platform to help you deploy with confidence.

Product

FeaturesPricingDocumentation

© 2025 Flagdeck. All rights reserved.