How to Implement Contextual Feature Flags in SvelteKit using Unleash
Tags: webdev, javascript, programming, tutorial
Published: 2024-02-01 14:03:49

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](https://kit.svelte.dev) 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](https://www.linkedin.com/in/rishi-raj-jain/)** as a part of the **[Community Content Program](https://github.com/unleash/community-content)**. You can also suggest a topic by [opening an issue](https://github.com/Unleash/community-content/issues), or [Write for Unleash](https://www.getunleash.io/blog/get-published-through-unleashs-community-content-program) as a part of the Community Content Program.

## What we’ll be using

- [SvelteKit](https://kit.svelte.dev) (UI and API Routes)
- [Vercel](https://vercel.com) (Edge Network)
- [Unleash](https://getunleash.io) (Feature Flags)
- [Tailwind CSS](https://tailwindcss.com) (Styling)

## What you'll need

- [Docker](https://docker.com)
- [Node.js 18](https://nodejs.org) (make sure npm works correctly)
- A [Vercel](https://vercel.com) account

## 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:

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

## 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:

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

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

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

```bash
Username: admin
Password: unleash4all
```

## Create a New Feature Flag

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

![Create a new feature flag in Unleash](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ahah0eoujb6z7e2yo332.png)

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

![View Feature Flag Dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cjmht06tg9zfxdsrfbn9.png)

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

![Click Save to go with default config](https://ik.imagekit.io/vjeqenuhn/test-2/Screenshot%202024-01-30%20at%207.51.00%E2%80%AFPM.png?updatedAt=1706624488076)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/35l67vut3ekxqcop43w7.png)

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

![Context Fields Table](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6klwe34tg5lwzxi0b69m.png)

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

![Define Custom Context Field](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0fs9uxa6bvqmketscqnm.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0m1wxaz8ihjj6zujlcmm.png)

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

![Enable Developement Environment Flag](https://ik.imagekit.io/vjeqenuhn/test-2/Screenshot%202024-02-01%20at%206.50.29%E2%80%AFPM.png)

## 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:

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

### 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.

```typescript
// 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>
```

### 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.


```typescript
// 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}
```

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.

```typescript
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 }
}
```

- Create a map of the 2 letter country code to the language used in them:

```typescript
// 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",
}
```

- Pass the language as context (in `unleashConfig`) to the Wrapper component (`FlagProvider`): 

```diff
<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>
```

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](https://ik.imagekit.io/vjeqenuhn/test-2/Screenshot%202024-02-01%20at%207.19.42%E2%80%AFPM.png)

## 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](https://www.getunleash.io/pricing).

2. Get an [API key](/reference/api-tokens-and-client-keys) 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](https://docs.getunleash.io/topics/feature-flags/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.