Svelte SDK

View as Markdown

The Unleash Svelte SDK lets you evaluate feature flags in Svelte applications. It connects to Unleash or Unleash Edge to fetch evaluated flags for a given Unleash context.

You can use this SDK with Unleash Enterprise or Unleash Open Source.

For an overview of how Unleash SDKs work, including offline behavior, feature compatibility across SDKs, and default refresh and metrics intervals, refer to the SDK overview.

Installation

$npm install @unleash/proxy-client-svelte

Initialization

To use this SDK, you need:

Import the provider like this in your entrypoint file (typically index.svelte):

1<script lang="ts">
2 import { FlagProvider } from '@unleash/proxy-client-svelte';
3
4 const config = {
5 url: '<unleash-url>/api/frontend', // Your Frontend API or Unleash Edge URL
6 clientKey: '<your-token>', // Frontend API token
7 refreshInterval: 15, // How often (in seconds) the client should poll for updates
8 appName: 'your-app-name' // The name of your application. It's only used for identifying your application
9 };
10</script>
11
12<FlagProvider {config}>
13 <App />
14</FlagProvider>

Connection options

Set url to the /api/frontend endpoint of your Unleash instance or your Unleash Edge instance. Set clientKey to a frontend API token.

Check flags

To check if a feature is enabled:

1<script lang="ts">
2 import { useFlag } from '@unleash/proxy-client-svelte';
3
4 const enabled = useFlag('travel.landing');
5</script>
6
7{#if $enabled}
8 <SomeComponent />
9{:else}
10 <AnotherComponent />
11{/if}

Check variants

To check variants:

1<script lang="ts">
2 import { useVariant } from '@unleash/proxy-client-svelte';
3
4 const variant = useVariant('travel.landing');
5</script>
6
7{#if variant.enabled && variant.name === 'SomeComponent'}
8 <SomeComponent />
9{:else if variant.enabled && variant.name === 'AnotherComponent'}
10 <AnotherComponent />
11{:else}
12 <DefaultComponent />
13{/if}

Defer rendering until flags fetched

useFlagsStatus retrieves the ready state and error events. Follow the following steps in order to delay rendering until the flags have been fetched.

1<script lang="ts">
2 import { useFlagsStatus } from '@unleash/proxy-client-svelte';
3
4 const { flagsReady, flagsError } = useFlagsStatus();
5</script>
6
7{#if !$flagsReady}
8 <Loading />
9{:else}
10 <MyComponent error={flagsError} />
11{/if}

Unleash context

Initial context can be specified on a FlagProvider config.context property.

<FlagProvider config={{ ...config, context: { userId: 123 }}>

This code sample shows you how to update the unleash context dynamically:

1<script lang="ts">
2 import { useUnleashContext, useFlag } from '@unleash/proxy-client-svelte';
3
4 export let userId;
5
6 const toggle = useFlag('my-toggle');
7 const updateContext = useUnleashContext();
8
9 $: {
10 // context is updated with userId
11 updateContext({ userId });
12 }
13
14 // OR if you need to perform an action right after new context is applied
15 $: {
16 async function run() {
17 // Can wait for the new flags to pull in from the different context
18 await updateContext({ userId });
19 console.log('new flags loaded for', userId);
20 }
21 run();
22 }
23</script>

Deferring client start

By default, the Unleash client will start polling for toggles immediately when the FlagProvider component renders. You can prevent it by setting startClient prop to false. This is useful when you’d like to for example bootstrap the client and work offline.

Deferring the client start gives you more fine-grained control over when to start fetching the feature toggle configuration. This could be handy in cases where you need to get some other context data from the server before fetching toggles, for instance.

To start the client, use the client’s start method. The below snippet of pseudocode will defer polling until the end of the asyncProcess function.

1<script lang="ts">
2 const client = new UnleashClient({
3 /* ... */
4 });
5
6 onMount(async () => {
7 // do async work ...
8 client.start();
9 });
10</script>
11
12<FlagProvider unleashClient={client} startClient={false}>
13 <App />
14</FlagProvider>

Use Unleash client directly

1<script lang="ts">
2 import { useUnleashContext, useUnleashClient } from '@unleash/proxy-client-svelte';
3
4 export let userId;
5
6 const client = useUnleashClient();
7
8 const login = () => {
9 // login user
10 if (client.isEnabled('new-onboarding')) {
11 // Send user to new onboarding flow
12 } else {
13 // send user to old onboarding flow
14 }
15 };
16</script>
17
18<LoginForm {login} />