Skip to main content

Svelte SDK

Use Toggly's Svelte SDK in Svelte applications.

Requirements​

The package supports Svelte ^4.0.0 || ^5.0.0. Packed consumer builds cover the declared Svelte 4.0.0 minimum, Svelte 4.2.20, and Svelte 5.57.0. Use the Svelte 5 toolchain on Node ^20.19, ^22.12, or >=24 when building a current Svelte 5 host.

Installation​

Install the Svelte feature flags package using NPM:

$ npm i -s @ops-ai/svelte-feature-flags-toggly

Basic Usage (with Toggly.io)​

Initialize Toggly​

Import and initialize Toggly in your main application file (typically App.svelte or main.ts):

import { createToggly } from '@ops-ai/svelte-feature-flags-toggly'

// Initialize with your App Key & Environment name from your Toggly application page
await createToggly({
appKey: 'your-app-key', // You can find this in app.toggly.io
environment: 'your-environment-name', // You can find this in app.toggly.io
onError: (message, error) => {
// Report fetch/cache/refresh failures to your monitoring provider
console.warn('Toggly error:', message, error)
},
})

Using the Feature Component​

Now you can start using the Feature component anywhere in your application:

<script>
import { Feature } from '@ops-ai/svelte-feature-flags-toggly'
</script>

<Feature featureKey="firstFeature">
<p>This feature can be turned on or off.</p>
</Feature>

Feature Component Options​

You can also check multiple feature keys and make use of the requirement (all/any) and negate (bool) options (requirement is set to "all" by default).

Show if all features are on​

<Feature featureKeys={['firstFeature', 'secondFeature']}>
<p>ALL the provided feature keys are TRUE.</p>
</Feature>

Show if any feature is on​

<Feature featureKeys={['firstFeature', 'secondFeature']} requirement="any">
<p>AT LEAST ONE the provided feature keys is TRUE.</p>
</Feature>

Show if features are off (negate)​

<Feature featureKeys={['firstFeature', 'secondFeature']} negate={true}>
<p>NONE of the provided feature keys is TRUE.</p>
</Feature>

Feature vs FeatureGateBuilder​

NeedUse
Remove content from the DOM when off<Feature>
Keep content mounted; drive CSS, disabled state, or handlers<FeatureGateBuilder>

Use <Feature> for show/hide. Use <FeatureGateBuilder> when you need the resolved boolean for styling, taps, or behavior:

<script>
import { FeatureGateBuilder } from '@ops-ai/svelte-feature-flags-toggly'
</script>

<FeatureGateBuilder featureKey="PremiumCheckout" let:enabled>
<button class:active={enabled} disabled={!enabled}>Checkout</button>
</FeatureGateBuilder>

For reactive stores, createFeatureStore and evaluateFeatureGate from the package also respect device-local post-filter gates when local gates revision changes.

Programmatic Feature Checks​

You can also check features programmatically using the store functions:

<script>
import { isFeatureOn, isFeatureOff, evaluateFeatureGate } from '@ops-ai/svelte-feature-flags-toggly'

let featureEnabled = false

async function checkFeature() {
featureEnabled = await isFeatureOn('myFeature')
}

async function checkMultipleFeatures() {
const result = await evaluateFeatureGate(['feature1', 'feature2'], 'any', false)
console.log('Gate result:', result)
}
</script>

<button on:click={checkFeature}>Check Feature</button>
{#if featureEnabled}
<p>Feature is enabled!</p>
{/if}

Using Reactive Stores​

You can also use Svelte stores for reactive feature flag checks:

<script>
import { createFeatureStore } from '@ops-ai/svelte-feature-flags-toggly'

const myFeature = createFeatureStore('myFeature')
</script>

{#if $myFeature}
<p>Feature is enabled!</p>
{/if}

Users and Rollouts​

Using this package with Toggly allows you to define custom feature rollouts.

Custom rollouts offers the ability to show features only to certain groups of users based on various custom rules which you can define in Toggly.

In case you want to support custom feature rollouts, remember to provide an unique identity string for each user to make sure they get the same feature values on future visits:

await createToggly({
appKey: 'your-app-key', // You can find this in app.toggly.io
environment: 'your-environment-name', // You can find this in app.toggly.io
identity: 'unique-user-identifier', // Use this in case you want to support custom feature rollouts
// Optional init-time targeting (also accepted on setContext below)
groups: ['beta', 'enterprise'],
claims: { role: 'admin', plan: 'premium' },
})

For User Claims and group targeting after login, call setContext() on the service:

import { getTogglyService } from '@ops-ai/svelte-feature-flags-toggly'

await getTogglyService().setContext({
identity: user.id,
groups: user.groups,
claims: { role: user.role, plan: user.plan },
})

See Feature filters and Evaluated-signed.

success

When using user identifiers, evaluated features are cached per user for 30 minutes by default on a sliding window, so the user might not see the change right away as to not confuse the user. The session length is configurable and the session store can be cleared in App Settings

Live updates and signed definitions​

WebSocket live updates are on by default. Pass enableLiveUpdates: false to poll only. Enable envelope verification with verifySignatures: true:

await createToggly({
appKey: 'your-app-key',
environment: 'your-environment-name',
enableLiveUpdates: true, // default
verifySignatures: true,
})

See WebSocket sync and Evaluated-signed.

Basic Usage (without Toggly.io)​

You can also use the Svelte SDK without connecting to Toggly.io by providing feature defaults:

Initialize with Defaults​

import { createToggly } from '@ops-ai/svelte-feature-flags-toggly'

const featureDefaults = {
firstFeature: true,
secondFeature: false,
}

await createToggly({
featureDefaults: featureDefaults,
})

Now you can use the Feature component the same way as with Toggly.io:

<Feature featureKey="firstFeature">
<p>This feature can be turned on or off.</p>
</Feature>

Configuration Options​

The createToggly function accepts the following options:

interface TogglyOptions {
baseURI?: string // Base URI for Toggly API (default: 'https://definitions.toggly.io')
appKey?: string // Your Toggly app key
environment?: string // Environment name (default: 'Production')
identity?: string // User identity for targeting
groups?: string[] // User groups for targeting
claims?: Record<string, string> // User claims for targeting
featureDefaults?: { [key: string]: boolean } // Default feature values
showFeatureDuringEvaluation?: boolean // Show feature while evaluating (default: false)
featureFlagsRefreshInterval?: number // Cache refresh interval in ms (default: 180000)
persistCache?: boolean // Cache flags/variants in localStorage (default: true)
maxCacheKeys?: number | null // LRU cap for identity-scoped cache keys (default: unlimited)
enableLiveUpdates?: boolean // WebSocket live updates (default: true)
verifySignatures?: boolean // Verify ES256 signed envelopes (default: false)
allowedKeyIds?: string[] // Optional JWKS kid allow-list
maxSignatureAgeSeconds?: number | null // Optional signature freshness window
onError?: (message: string, error?: unknown) => void // SDK error callback
}

For maxCacheKeys behavior, see Client-side cache limits.

Error reporting and refresh behavior​

Pass onError to createToggly() to observe fetch, cache, parse, and refresh failures:

await createToggly({
appKey: 'your-app-key',
environment: 'your-environment-name',
onError: (message, error) => {
monitoring.captureException(error, {
tags: { source: 'toggly' },
extra: { message }
});
},
});

The service exposes lastError, which is updated before onError runs. After one successful load, refresh failures preserve the last-known-good flags instead of replacing rendered content with defaults or empty flags. <Feature> and reactive stores subscribe to flag refreshes, so interval and WebSocket updates can re-render Svelte UI automatically.

For the shared reliability contract, see Reliability and Error Handling.

SvelteKit Integration​

For request-scoped server evaluation, load/action guards and hydration, use the dedicated SvelteKit SDK. The following integration uses this Svelte package only in the browser after mounting:

<!-- src/routes/+layout.svelte -->
<script>
import { onMount } from 'svelte'
import { createToggly } from '@ops-ai/svelte-feature-flags-toggly'

onMount(async () => {
await createToggly({
appKey: 'your-app-key',
environment: 'Production',
identity: 'user-123' // Get from session/auth
})
})
</script>

<slot />

TypeScript Support​

The Svelte SDK includes full TypeScript support with type definitions:

import {
Feature,
createToggly,
isFeatureOn,
type TogglyOptions
} from '@ops-ai/svelte-feature-flags-toggly'

const config: TogglyOptions = {
appKey: 'your-app-key',
environment: 'Production',
identity: 'user-123'
}

await createToggly(config)

Best Practices​

  1. Initialize Once: Call createToggly() once at the root of your app
  2. Use Feature Component: Prefer using the Feature component for declarative feature flag checks
  3. Provide User Context: Include identity for accurate targeting and rollouts
  4. Set Feature Defaults: Provide defaults for offline scenarios or when not using Toggly.io
  5. TypeScript: Take advantage of TypeScript support for better type safety
  6. Reactive Stores: Use createFeatureStore() for reactive feature flag checks in your components

API Reference​

createToggly(config: TogglyOptions): Promise<void>​

Initializes the Toggly service and loads feature flags.

<Feature>​

Svelte component for conditional rendering based on feature flags.

Props:

  • featureKey?: string - Single feature key to check
  • featureKeys?: string[] - Multiple feature keys to check
  • requirement?: 'all' | 'any' - Requirement type (default: 'all')
  • negate?: boolean - Whether to negate the result (default: false)

isFeatureOn(featureKey: string): Promise<boolean>​

Check if a feature is enabled.

isFeatureOff(featureKey: string): Promise<boolean>​

Check if a feature is disabled.

evaluateFeatureGate(featureKeys: string[], requirement?: 'all' | 'any', negate?: boolean): Promise<boolean>​

Evaluate a feature gate with multiple flags.

createFeatureStore(featureKey: string)​

Create a reactive Svelte store for a specific feature flag.

Extensibility with Hooks​

Toggly provides a powerful hooks system that allows you to extend SDK functionality by hooking into feature flag lifecycle events. This is perfect for integrating with analytics platforms like Microsoft Clarity, monitoring tools, or implementing custom behaviors.

What are Hooks?​

Hooks let you execute custom code at specific points in the feature flag evaluation lifecycle:

  • beforeEvaluation: Called before a feature flag is evaluated
  • afterEvaluation: Called after a feature flag is evaluated (with the result)
  • beforeIdentify: Called before user identity is set or cleared
  • afterIdentify: Called after user identity is set or cleared
  • afterRefresh: Called after feature definitions are refreshed from Toggly

Creating a Hook​

import { Hook } from '@ops-ai/toggly-hooks-types';

const myAnalyticsHook: Hook = {
getMetadata: () => ({
name: 'MyAnalyticsHook',
version: '1.0.0'
}),

afterEvaluation: async (flagKey, _data, result) => {
// Send to analytics
analytics.track('Feature Flag Evaluated', {
feature: flagKey,
enabled: result
});
}
};

Registering Hooks​

During initialization:​

import { createToggly } from '@ops-ai/svelte-feature-flags-toggly';

await createToggly({
appKey: 'your-app-key',
environment: 'your-environment-name',
hooks: [myAnalyticsHook]
});

At runtime:​

import { getTogglyService } from '@ops-ai/svelte-feature-flags-toggly';

// After the initialization above has completed.
const togglyService = getTogglyService();

// Add a hook
togglyService.addHook(myAnalyticsHook);

// Remove a hook
togglyService.removeHook(myAnalyticsHook.getMetadata().name);

In a Svelte component:​

<script lang="ts">
import { onMount } from 'svelte';
import { getTogglyService } from '@ops-ai/svelte-feature-flags-toggly';
import type { Hook } from '@ops-ai/toggly-hooks-types';

const analyticsHook: Hook = {
getMetadata: () => ({ name: 'Analytics', version: '1.0.0' }),
afterEvaluation: async (flagKey, _data, result) => {
// Your analytics logic
console.log('Feature evaluated:', flagKey, result);
}
};

// Mount this component after the app has awaited createToggly().
onMount(() => {
const togglyService = getTogglyService();
togglyService.addHook(analyticsHook);
return () => {
togglyService.removeHook(analyticsHook.getMetadata().name);
};
});
</script>

Common Use Cases​

Microsoft Clarity Integration​

import type { Hook } from '@ops-ai/toggly-hooks-types';

const clarityHook: Hook = {
getMetadata: () => ({ name: 'Microsoft Clarity', version: '1.0.0' }),
afterEvaluation: async (flagKey, _data, result) => {
if (typeof clarity !== 'undefined') {
clarity('event', `FeatureFlag:${flagKey}`);
}
}
};

Svelte Store Integration​

import { writable } from 'svelte/store';
import { Hook } from '@ops-ai/toggly-hooks-types';

const featureEvaluations = writable<Array<{key: string, result: boolean}>>([]);

const storeHook: Hook = {
getMetadata: () => ({ name: 'StoreHook', version: '1.0.0' }),
afterEvaluation: async (flagKey, _data, result) => {
featureEvaluations.update(items => [
...items,
{ key: flagKey, result: result }
]);
}
};

Entity context​

Pass a page entity per widget or check — not via global user setContext() / identity. See Entity & page context.

The Svelte SDK is a client: pass entity attributes locally. It does not PUT context schemas to the dashboard.

// Canonical context travels with this one entity evaluation.
const orderContext = {
kind: 'Order',
key: String(order.id),
attributes: { Status: order.status, Total: order.total },
}
<script>
import { Feature } from '@ops-ai/svelte-feature-flags-toggly'
export let order
$: orderContext = { kind: 'Order', key: String(order.id),
attributes: { Status: order.status, Total: order.total } }
</script>

<Feature featureKey="OrderBadge" context={orderContext}>
<span class="badge">Featured</span>
</Feature>

Evaluated-signed may return true, false, or an { requirement, rules } gate. Without entity context, gates fail closed. setContext / identity remains user only.

See also​

Sample references​

Browse the Toggly Samples catalog for hands-on examples. Start with a sample’s README for setup instructions, then follow its source walkthrough to see how configuration, flag checks, and UI behavior fit together.

Next Steps​