Sveltev1.2.1Frontend

Svelte SDK

Add feature flags to your Svelte application with reactive stores and context. Wraps @rollgate/sdk-browser with Svelte-native store bindings for seamless reactivity.

Installation

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

Quick Start

1. Set Up Context

Create a Rollgate instance and set the context in your root layout so all child components can access feature flags:

+layout.svelte
<script>
  import { createRollgate, setRollgateContext } from '@rollgate/sdk-svelte';

  const rollgate = createRollgate({
    apiKey: 'rg_client_...',
    baseUrl: 'https://api.rollgate.io',
  });

  setRollgateContext(rollgate);
</script>

<slot />

2. Use Feature Flags

Access flags in any child component with getFlag:

Component.svelte
<script>
  import { getFlag } from '@rollgate/sdk-svelte';

  const isEnabled = getFlag('my-feature', false);
</script>

{#if $isEnabled}
  <NewFeature />
{/if}

Note: The $ prefix is Svelte's auto-subscription syntax. It automatically subscribes and unsubscribes from the store, keeping your component reactive.

Configuration

Pass configuration options to createRollgate():

PropTypeDefaultDescription
apiKeystringrequiredYour Rollgate client API key
baseUrlstring'https://api.rollgate.io'Rollgate API base URL
refreshIntervalnumber30000Polling interval in milliseconds
enableStreamingbooleanfalseUse SSE for real-time updates (opt-in)
streamingbooleanfalseAlias for enableStreaming
Example with all options
const rollgate = createRollgate({
  apiKey: 'rg_client_...',
  baseUrl: 'https://api.rollgate.io',
  refreshInterval: 15000,
  enableStreaming: true,
});

Stores

The SDK provides three convenience functions that use Svelte context internally. These must be called from a component that is a child of the one where setRollgateContext was called.

getFlag

Returns a reactive Readable store for a single flag:

import { getFlag } from '@rollgate/sdk-svelte';

const showBanner = getFlag('promo-banner', false);
// Use as $showBanner in template
PropTypeDefaultDescription
flagKeystringrequiredThe flag key to check
defaultValuebooleanfalseValue to return if flag not found

getFlags

Returns a reactive store for multiple flags at once:

import { getFlags } from '@rollgate/sdk-svelte';

const features = getFlags(['feature-a', 'feature-b', 'feature-c']);

// In template:
// {#if $features['feature-a']}...{/if}

getRollgate

Access the full Rollgate context for advanced use cases like identifying users, refreshing flags, or reading loading/error state:

import { getRollgate } from '@rollgate/sdk-svelte';

const { identify, refresh, isLoading, isError, isStale, flags } = getRollgate();

// Identify user after login
await identify({
  id: 'user-123',
  email: '[email protected]',
  attributes: { plan: 'pro' },
});

// Force refresh
await refresh();

Available Store Properties

The object returned by createRollgate() and getRollgate() contains:

PropTypeDefaultDescription
flagsReadable<Record<string, boolean>>-Reactive store of all flags
isLoadingReadable<boolean>-True while initial flags are loading
isErrorReadable<boolean>-True if last fetch failed
isStaleReadable<boolean>-True if serving cached/stale flags
isReadyReadable<boolean>-True after first successful load
circuitStateReadable<CircuitState>-Circuit breaker state (CLOSED, OPEN, HALF_OPEN)
flag(key, default)(string, boolean) => Readable<boolean>-Create a reactive store for a single flag
isEnabled(key, default)(string, boolean) => boolean-Non-reactive flag check (snapshot)
isEnabledDetail(key, default)(string, boolean) => EvaluationDetail-Flag check with evaluation reason
identify(user)(UserContext) => Promise<void>-Set user context for targeting
reset()() => Promise<void>-Clear user context
refresh()() => Promise<void>-Force refresh all flags
getMetrics()() => MetricsSnapshot-Get SDK metrics (cache hits, errors, etc.)
close()() => void-Close the client and release resources

User Targeting

Pass user information to enable targeting rules, percentage rollout, and target user lists. The SDK sends this context to the server where rules are evaluated securely.

User Context Structure

interface UserContext {
  id: string;           // Required for percentage rollout
  email?: string;       // For email-based targeting
  attributes?: {        // Any custom attributes for targeting rules
    plan?: string;      // e.g., "free", "pro", "growth"
    country?: string;   // e.g., "IT", "US", "DE"
    company?: string;   // e.g., "Acme Inc"
    app_version?: string; // e.g., "2.1.0" (for semver comparisons)
    [key: string]: string | number | boolean;
  };
}

Setting User at Initialization

+layout.svelte
<script>
  import { createRollgate, setRollgateContext } from '@rollgate/sdk-svelte';

  const rollgate = createRollgate(
    {
      apiKey: 'rg_client_...',
      baseUrl: 'https://api.rollgate.io',
    },
    {
      id: 'user-123',
      email: '[email protected]',
      attributes: {
        plan: 'pro',
        country: 'IT',
        company: 'Acme Inc',
        app_version: '2.1.0',
      },
    }
  );

  setRollgateContext(rollgate);
</script>

<slot />

Setting User Dynamically

LoginHandler.svelte
<script>
  import { getRollgate } from '@rollgate/sdk-svelte';

  const { identify } = getRollgate();

  async function onLogin(user) {
    await identify({
      id: user.id,
      email: user.email,
      attributes: {
        plan: user.subscription.plan,
        country: user.profile.country,
        company: user.organization?.name,
      },
    });
  }
</script>

Security: Rules are evaluated server-side. Users cannot see or manipulate the targeting logic - they only receive the final boolean result.

SvelteKit Integration

For SvelteKit apps, set up the context in your root layout and access flags in any page or component.

Root Layout

src/routes/+layout.svelte
<script>
  import { createRollgate, setRollgateContext } from '@rollgate/sdk-svelte';
  import { PUBLIC_ROLLGATE_API_KEY } from '$env/static/public';

  const rollgate = createRollgate({
    apiKey: PUBLIC_ROLLGATE_API_KEY,
    baseUrl: 'https://api.rollgate.io',
  });

  setRollgateContext(rollgate);
</script>

<slot />

Page Component

src/routes/+page.svelte
<script>
  import { getFlag, getRollgate } from '@rollgate/sdk-svelte';

  const newDashboard = getFlag('new-dashboard', false);
  const { isLoading } = getRollgate();
</script>

{#if $isLoading}
  <LoadingSpinner />
{:else if $newDashboard}
  <NewDashboard />
{:else}
  <LegacyDashboard />
{/if}

Evaluation Reasons

Use isEnabledDetail to get the reason why a flag evaluated to a specific value:

DebugPanel.svelte
<script>
  import { getRollgate } from '@rollgate/sdk-svelte';

  const { isEnabledDetail } = getRollgate();

  const detail = isEnabledDetail('my-feature', false);
  // detail.value    -> boolean
  // detail.reason   -> { kind: 'FALLTHROUGH' | 'TARGET_MATCH' | 'OFF' | ... }
</script>

<p>Flag value: {detail.value}</p>
<p>Reason: {detail.reason.kind}</p>