Browserv1.2.1Frontend

Browser SDK

Framework-agnostic feature flags for web browsers with built-in polling, SSE streaming, circuit breaker, and caching. The core frontend SDK that React, Vue, Angular, and Svelte wrappers are built on.

15 KB

Lightweight

3.7 KB gzipped

🔄

Polling & SSE

Real-time updates

🛡️

Circuit Breaker

Auto-recovery

🎯

User Targeting

Personalized flags

Installation

npm install @rollgate/sdk-browser
# or
yarn add @rollgate/sdk-browser
# or
pnpm add @rollgate/sdk-browser

Quick Start

src/flags.js
import { RollgateClient } from '@rollgate/sdk-browser';

const rollgate = new RollgateClient({
  apiKey: 'rg_client_...',
  baseUrl: 'https://api.rollgate.io',
  refreshInterval: 30000, // Poll every 30s
});

await rollgate.init();

// Check flags
const isEnabled = rollgate.isEnabled('my-feature', false);

// Identify user for targeting
await rollgate.identify({
  id: 'user-123',
  email: '[email protected]',
  attributes: { plan: 'pro' }
});

// Listen for changes
rollgate.on('flags-updated', (flags) => {
  console.log('Flags updated:', flags);
});

// Cleanup
rollgate.close();

Configuration

OptionTypeDefaultDescription
apiKeystringrequiredClient API key (rg_client_...)
baseUrlstring'https://api.rollgate.io'API base URL
refreshIntervalnumber30000Polling interval (ms), 0 to disable
streamingbooleanfalseEnable SSE for real-time flag updates
timeoutnumber5000Request timeout (ms)
startWaitTimeMsnumber5000Max time to wait for initialization (ms)
initCanFailbooleanfalseIf true, initialization resolves even on failure

Methods

init()

Initialize the client, fetch flags, and start polling or streaming. Returns a promise that resolves when flags are loaded.

await rollgate.init();

// Or with error handling
try {
  await rollgate.init();
  console.log('Flags loaded:', Object.keys(rollgate.getAllFlags()).length);
} catch (error) {
  console.error('Init failed:', error.message);
  // App continues with default flag values
}

isEnabled(key, defaultValue)

Check if a boolean flag is enabled. Returns the flag value or the default.

const showFeature = rollgate.isEnabled('new-feature', false);

if (showFeature) {
  // Show new feature UI
}

getValue<T>(key, defaultValue)

Get a flag value of any type. Use for string, number, or JSON flags.

// String flag
const theme = rollgate.getValue('theme', 'light');

// Number flag
const maxItems = rollgate.getValue('max-items', 10);

// JSON flag
const config = rollgate.getValue('ui-config', { showBanner: false });

getString(key, defaultValue)

Type-safe helper for string flags.

const buttonColor = rollgate.getString('cta-color', 'blue');
const variant = rollgate.getString('checkout-variant', 'control');

getNumber(key, defaultValue)

Type-safe helper for number flags.

const pageSize = rollgate.getNumber('results-per-page', 20);
const timeout = rollgate.getNumber('api-timeout-ms', 5000);

getJSON<T>(key, defaultValue)

Type-safe helper for JSON flags with generic type support.

const config = rollgate.getJSON('feature-config', {
  enabled: false,
  maxItems: 10,
  allowedRoles: ['admin']
});

if (config.enabled) {
  // Use config values
}

getAllFlags()

Get all flags as an object.

const flags = rollgate.getAllFlags();
// { 'feature-a': true, 'feature-b': false, 'theme': 'dark' }

identify(user)

Set user context for targeting rules. Re-fetches flags with the new context.

await rollgate.identify({
  id: 'user-123',
  email: '[email protected]',
  attributes: {
    plan: 'enterprise',
    country: 'US',
    company: 'Acme Inc',
    app_version: '2.1.0',
  }
});

refresh()

Force refresh flags from the server.

await rollgate.refresh();

close()

Clean up all resources: stop polling, close SSE connections, clear event listeners.

// Call when your app unmounts or the user logs out
rollgate.close();

Event Listeners

Subscribe to SDK events using on() and unsubscribe with off().

// Fires when the client is initialized and flags are loaded
rollgate.on('ready', () => {
  console.log('Rollgate is ready');
});

// Fires when a specific flag changes value
rollgate.on('flag-changed', (key, newValue) => {
  console.log(`Flag ${key} changed to ${newValue}`);
});

// Fires when flags are refreshed (polling or SSE)
rollgate.on('flags-updated', (flags) => {
  console.log('All flags:', flags);
});

// Fires on API errors
rollgate.on('error', (error) => {
  console.error('Rollgate error:', error.message);
});

// Fires when circuit breaker state changes
rollgate.on('circuit-state-change', (state) => {
  console.log('Circuit breaker:', state);
});

// Unsubscribe from an event
const handler = (flags) => console.log(flags);
rollgate.on('flags-updated', handler);
rollgate.off('flags-updated', handler);

User Targeting

User context enables server-side targeting rule evaluation. Rules are defined in the dashboard and evaluated on the server - the client never sees the targeting logic.

User identification
// Identify when user logs in
async function onLogin(user) {
  await rollgate.identify({
    id: user.id,
    email: user.email,
    attributes: {
      plan: user.subscription?.plan || 'free',
      country: user.country,
      company: user.organization?.name,
      app_version: APP_VERSION,
    }
  });

  // Flags are now personalized for this user
  const showPremium = rollgate.isEnabled('premium-feature', false);
}

// Reset when user logs out
async function onLogout() {
  await rollgate.reset();
}

Available operators: equals, not_equals, contains, starts_with, ends_with, in, not_in, gt, gte, lt, lte, regex, is_set, is_not_set, semver_gt, semver_lt, semver_eq

Circuit Breaker

The SDK includes a circuit breaker that protects your app when Rollgate is unavailable. When open, it uses cached flag values so your app continues to work.

// Get current state
const state = rollgate.getCircuitState();
// 'closed' | 'open' | 'half-open'

// Listen to state changes
rollgate.on('circuit-state-change', (data) => {
  if (data.to === 'open') {
    console.warn('Using cached flags - Rollgate unavailable');
  }
  if (data.to === 'closed') {
    console.log('Connection restored');
  }
});

Error Handling

The SDK never throws exceptions during flag evaluation. If Rollgate is unavailable, flags return their default values. The circuit breaker and caching ensure your app remains functional.

Graceful degradation
// Default values ensure your app works without Rollgate
const showFeature = rollgate.isEnabled('new-feature', false);
// Returns false if: flag doesn't exist, API down, circuit open

// Monitor SDK health
rollgate.on('error', (error) => {
  analytics.track('rollgate_error', { message: error.message });
});

rollgate.on('circuit-state-change', (state) => {
  if (state.to === 'open') {
    analytics.track('rollgate_circuit_open');
  }
});

Vanilla JavaScript Example

app.js
import { RollgateClient } from '@rollgate/sdk-browser';

const rollgate = new RollgateClient({
  apiKey: 'rg_client_...',
  baseUrl: 'https://api.rollgate.io',
  refreshInterval: 30000,
});

// Wait for flags to load
await rollgate.init();

// Render UI based on flags
function render() {
  const app = document.getElementById('app');

  if (rollgate.isEnabled('new-hero', false)) {
    app.innerHTML = '<h1>Welcome to the new experience!</h1>';
  } else {
    app.innerHTML = '<h1>Welcome!</h1>';
  }

  const theme = rollgate.getString('theme', 'light');
  document.body.className = `theme-${theme}`;
}

// Re-render when flags change
rollgate.on('flags-updated', () => render());

// Initial render
render();

// Identify user after login
document.getElementById('login-form').addEventListener('submit', async (e) => {
  e.preventDefault();
  const userId = e.target.elements.userId.value;

  await rollgate.identify({
    id: userId,
    attributes: { source: 'web' }
  });

  render();
});

Framework SDKs

If you are using a frontend framework, we recommend using the framework-specific SDK instead of this package directly. Each framework SDK wraps @rollgate/sdk-browser and provides idiomatic integration with the framework's reactivity system.

FrameworkPackageFeatures
React@rollgate/sdk-reactHooks, Provider, Context
Vue@rollgate/sdk-vueComposables, Plugin
Angular@rollgate/sdk-angularService, Module, Directives
Svelte@rollgate/sdk-svelteStores, Context

When to use @rollgate/sdk-browser directly: Use this package for vanilla JavaScript apps, Web Components, or any non-framework environment. For React, Vue, Angular, or Svelte projects, the framework SDKs provide better developer experience with reactive bindings and hooks.