Unleash / community-content

Community Content Program for users to be able to contribute to Unleash.
1 stars 0 forks source link

docs: How to Implement Feature Flags in SvelteKit using Unleash #22

Closed rishi-raj-jain closed 5 months ago

rishi-raj-jain commented 8 months ago

Outline πŸ‘‡πŸ»


How to Implement Feature Flags in SvelteKit using Unleash

Some additional information

In this tutorial, you will learn how to use feature flags in a [SvelteKit](https://kit.svelte.dev/) application that shows a content in different languages based on their region, using Unleash. We will use the @unleash/proxy-client-svelte package, which provides easy integration of Unleash feature flags in a Svelte application.

What we’ll be using

Mention:

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/repo-slug
# Some additional information

Scaffolding a SvelteKit app

Creating an SvelteKit app is as easy as a single command:

# command

Setup Unleash

  1. Run the following commands in the terminal to fetch the docker-compose.yml for creating an Unleash instance:
wget getunleash.io/docker-compose.yml
docker-compose up -d

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

Create a Custom Context Field

To display different contents to the user based on the region, we'll be creating a custom constraint named region in Unleash. This will help us define the country values for which the translation would be possible and use that flag in our app.

Steps to create a custom field

Screenshots

Create a New Feature

Create a new feature flag in your Unleash instance named regional-content.

Steps to create use the custom field region

Screenshots

Integrating Unleash in SvelteKit app

Installation

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

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

npm install @unleash/proxy-client-svelte

Set up Environment Variables

By default, the following values are setup in your local Unleash instance

# .env

UNLEASH_API_URL="http://localhost:4242/api"
UNLEASH_AUTHORIZATION_KEY="default:development.unleash-insecure-api-token"

Initialize Unleash SDK

Some additional information

Initialise Unleash SDK

Some additional information

// some code

Use Unleash SDK to fetch the feature flag value

Some additional information

// some code

Scenarios

Some additional information

Screenshots

Revert: Scenarios

Some additional information

Screenshots

Using Unleash in Production

To setup 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](https://github.com/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.

Conclusion

Some additional information

nnennandukwe commented 5 months ago

This looks like a great outline structure. πŸ‘

rishi-raj-jain commented 5 months ago

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

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

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

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

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>

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}

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:

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

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.

nunogois commented 5 months ago

Some notes:

I suggest submitting it as a PR next time, so it's easier to review πŸ‘

nunogois commented 5 months ago

I noticed a few things with your example repo:

image

rishi-raj-jain commented 5 months ago

@nunogois

This is such a super detailed feedback!

I've updated the code & the blog to reflect all the changes πŸ™πŸ»

rishi-raj-jain commented 5 months ago

I suggest submitting it as a PR next time, so it's easier to review πŸ‘

I did it earlier, but it creates confusion as seen in: https://github.com/Unleash/unleash/pull/5246#issuecomment-1877520375

nunogois commented 5 months ago

Great job addressing my notes @rishi-raj-jain, I think this is better!

I still feel a bit of a disconnect in the flow.

Try putting yourself in the shoes of a completely new user with no context. If you follow your guide step by step, you'll end up with an unleash folder inside the regional-content-unleash-and-sveltekit folder, which is probably not what we want. We're also cloning your regional-content-unleash-and-sveltekit project and installing its dependencies, but not really doing anything with it.

My suggestion is maybe restructuring the guide this way:

I think @nnennandukwe may be able to help with this and probably give you even better suggestions, so it may be worth waiting for her feedback before proceeding with any changes.

Other than that I'm mostly happy, thank you for taking my notes into consideration βœ…

nnennandukwe commented 5 months ago

This is awesome @rishi-raj-jain !

I have a few comments/tweaks to make, but nice to see the start and improvement from the feedback @nunogois gave!

Let me know if you have any questions about my comments!

rishi-raj-jain commented 5 months ago

@nunogois @nnennandukwe

Thank you so much for taking time to give a detailed one on this one!

I've done my best to incorporate all the feedback ✨

"Integrating Unleash in SvelteKit"

For this, it's not exactly just installing. One is learning how to walk through the entire integration of Unleash in SvelteKit, hence I named it on that...

rishi-raj-jain commented 5 months ago

Published at https://dev.to/reeshee/how-to-implement-contextual-feature-flags-in-sveltekit-using-unleash-nkf.

rishi-raj-jain commented 5 months ago

Socials πŸ‘‡πŸ»