DEV Community

Rishi Raj Jain
Rishi Raj Jain

Posted on

How to Implement Contextual Feature Flags in SvelteKit using Unleash

Feature flags are a powerful technique that allows you to toggle features on and off dynamically without redeploying your code. This can help you to deliver faster and safer web applications, as you can test new user journeys in production, perform gradual rollouts, and revert changes as required, all without triggering a redeploy.

In this tutorial, you will learn how to use custom feature flags in a SvelteKit application that displays regional content to the users based on the location they're accessing the site from, using Vercel and Unleash. You'll use the official Svelte SDK by Unleash, @unleash/proxy-client-svelte, which provides easy integration of Unleash feature flags in any Svelte application.

This article is a contribution by Rishi Raj Jain as a part of the Community Content Program. You can also suggest a topic by opening an issue, or Write for Unleash as a part of the Community Content Program.

What we’ll be using

What you'll need

Setting up the project

To set up, just clone the app repo and follow this tutorial to learn everything that's in it. To fork the project, run:



git clone https://github.com/rishi-raj-jain/regional-content-unleash-and-sveltekit
cd regional-content-unleash-and-sveltekit
npm install


Enter fullscreen mode Exit fullscreen mode

Set up Unleash

  1. Run the following commands in the terminal to fetch the docker-compose.yml for creating an Unleash instance outside of your current project directory:


git clone git@github.com:Unleash/unleash.git
cd unleash
docker compose up -d


Enter fullscreen mode Exit fullscreen mode

This will start Unleash in the background. Once Unleash is running, you can access it at http://localhost:4242.

  1. Now use the default credentials to log into the instance:


Username: admin
Password: unleash4all


Enter fullscreen mode Exit fullscreen mode

Create a New Feature Flag

Create a new feature flag in your Unleash instance named regional:

Create a new feature flag in Unleash

In the feature flag's dashboard, click on Add strategy in the developement environment:

View Feature Flag Dashboard

Click Save to associate the pre-configured setup with the regional feature flag.

Click Save to go with default config

Let's move to creating a custom context field region, for which we'll define a set of values that'll indicate the languages are supported with their translation in our app.

First, click on Configure in the navigation bar and then click on Context fields:

Configure in Navigation

You would then see a screen like below. Click on New Context Field button to create a custom field:

Context Fields Table

Now, enter the details of the custom field named region, such as HI and EN in this case.

Define Custom Context Field

Hit create context, and then go to your feature flag in the dashboard. Update the strategy to define the constraints to enforce region values.

Only users with one of these regions will see this flag as enabled.

Update the feature flag

Great. Now, let's turn on the flag in the developement environment 👇🏻

Enable Developement Environment Flag

Integrating Unleash with SvelteKit

Installation

To get started with SvelteKit and Unleash, you need to install @unleash/proxy-client-svelte package as a dependency in the project repository.

You can run the following commands in your terminal to do this:



npm install -D @unleash/proxy-client-svelte


Enter fullscreen mode Exit fullscreen mode

Initialize Unleash SDK

To make feature flags available to our SvelteKit application, we will create an Unleash Context component. This helper will initialize the Unleash Svelte SDK and provide access to feature flags throughout our application. We will do this by adding it to our src/routes/+page.svelte file.



// File: src/routes/+page.svelte

<script lang="ts">
    import Content from "../components/content.svelte";
    import { FlagProvider } from "@unleash/proxy-client-svelte";

    const unleashConfig = {
    // How often (in seconds) the client should poll the proxy for updates
    refreshInterval: 1,
    // The name of your application. It's only used for identifying your application
    appName: "customName",
    // Your front-end API URL or the Unleash proxy's URL (https://<proxy-url>/proxy)
    url: "http://localhost:4242/api/frontend",
    // A client-side (frontend) API token OR one of your proxy's designated client keys (previously known as proxy secrets)
    clientKey: "default:development.unleash-insecure-frontend-api-token",
  };
</script>

<FlagProvider config={unleashConfig}>
  <Content {language} />
</FlagProvider>


Enter fullscreen mode Exit fullscreen mode

Use Unleash Svelte SDK to fetch the feature flag value with context

Next, we will show regional content to the user if 1. the regional feature flag is enabled, and 2. the language in their region is allowed in the feature flag. Let's break it into steps:

1. Regional feature flag is enabled

To check if the regional feature flag is enabled for a user, we'll use useFlag hook.



// File: src/components/content.svelte

<script lang="ts">
  export let language: string;

  import { useFlag } from "@unleash/proxy-client-svelte";

  const isRegionTranslated = useFlag("regional");
</script>

{#if $isRegionTranslated}
  <div class="mt-3">
    <span class="py-2 px-4 bg-green-100 rounded">
      Content in <b>{language}</b>
    </span>
  </div>
{:else}
  <div class="mt-3">
    <span class="py-2 px-4 bg-red-100 rounded"> Fallback Content </span>
  </div>
{/if}


Enter fullscreen mode Exit fullscreen mode

Keep in mind that we've to set the region context with the regional to evaluate whether if their region is allowed (enabled) to be translated and shown to them. This all done via:

2. Pass language as context

To pass the language (HI OR EN) as the context while looking for regional flag, we'll update our Unleash Context Wrapper component to include the custom context value.

Here's how we'd do that:

  • Create a +page.server.ts that'll use the Vercel's x-vercel-ip-country header to determine the region the user is in.


import type { PageServerLoad } from './$types'

export const load: PageServerLoad = async ({ request }) => {
    // get the vercel IP country header containing 2 letter string for that country
    const region: string = request.headers.get('x-vercel-ip-country') || "US"
    return { region }
}


Enter fullscreen mode Exit fullscreen mode
  • Create a map of the 2 letter country code to the language used in them:


// place files you want to import through the `$lib` alias in this folder.

// create a super collection mapping country to the language used in that region
export const countryCodeMap: Record<string, string> = {
    "IN": "HI",
    "US": "EN",
}


Enter fullscreen mode Exit fullscreen mode
  • Pass the language as context (in unleashConfig) to the Wrapper component (FlagProvider):


<script lang="ts">
  /** @type {import('./$types').PageData} */
  export let data;

  import { countryCodeMap } from "$lib";
  import Content from "../components/content.svelte";
  import { FlagProvider } from "@unleash/proxy-client-svelte";

+  // use the dynamic country's region 2 letter code
+  const language = countryCodeMap[data.region];

  const unleashConfig = {
    // How often (in seconds) the client should poll the proxy for updates
    refreshInterval: 1,
    // The name of your application. It's only used for identifying your application
    appName: "customName",
    // Your front-end API URL or the Unleash proxy's URL (https://<proxy-url>/proxy)
    url: "http://localhost:4242/api/frontend",
    // A client-side (frontend) API token OR one of your proxy's designated client keys (previously known as proxy secrets)
    clientKey: "default:development.unleash-insecure-frontend-api-token",
+    // create custom Unleash context
+    context: { properties: { region: language } },
    // To test if the value should be returned false, uncomment below and comment above line
    // context: { properties: { region: "OP" } },
  };
</script>

<FlagProvider config={unleashConfig}>
  <Content {language} />
</FlagProvider>


Enter fullscreen mode Exit fullscreen mode

Awesome, now we're able to detect the location of the user per request, get the language spoken in their region and use that to determine if the feature flag is enabled for a user. Here's a preview of what we've made 👇🏻

Demo

Using Unleash in Production

To set up Unleash for production, please follow the steps below:

  1. Self-host Unleash, or run an instance on Unleash Cloud.

  2. Get an API key from the Unleash dashboard.

  3. Store the API key in your Environment Variables of your hosting, which secures it and makes it accessible in your code.

Unleash has a full list of feature flag best practices that can help guide you as you architect your solution.

Conclusion

Feature flags are a powerful tool for managing features in web applications. This tutorial showed us how to use feature flags with SvelteKit and Unleash. We have seen how to create custom context field in conjuction with how to manage feature flags in the Unleash dashboard, and how to use them in our SvelteKit code with the @unleash/proxy-client-svelte package.

Top comments (0)