Coder Social home page Coder Social logo

Comments (11)

nunogois avatar nunogois commented on June 28, 2024 2

Some notes:

  • You're using pnpm in your instructions, but pnpm is not part of the requirements to get started. Consider using Node's npm instead.
  • Why are we asking users to set up the project from the repo and then ask them to create a new project? There's something wrong with the flow. If I'm a new user and follow the guide as is, I'll end up with a new project inside a project I just cloned, which is confusing to say the least. (1)
  • wget is not included by default in most OSes. Consider @nnennandukwe's instructions here as an alternative.
  • "Click Save to associate the pre-configured setup with the regional feature flag." - Feels like we're missing a screenshot here.
  • "You would then see a screen like below. Click on New Context Field button to create a custom field:" - You're missing a step: Clicking "context fields".
  • "create conext" - typo
  • "This allows us to define the values of region that are supported with the feature flag named regional (that we created earlier)." - Maybe it's easier to include something like "Only users with one of these regions will see this flag as enabled"
  • "Integrating Unleash in SvelteKit" - Maybe this is the section that should include setting up a new SvelteKit project (1). Maybe with a note like "If you'd like to create your own SvelteKit project, you can follow these steps:"
  • "// A client-side API token OR one of your proxy's designated client keys (previously known as proxy secrets)" - Maybe it's easier for the users if you mention that this is a frontend token, like in our UI: "// A client-side (frontend) API token OR one of your proxy's designated client keys (previously known as proxy secrets)
  • Your imports look weird. Usually imports are the first things on a file.
  • Might be worth adding the flagsReady logic to the example, as that's usually a good practice.
  • "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:" - This reads a bit weird. Consider rephrasing.
  • "Aweosme" - typo
  • "setup" - typo, should be "set up" here
  • I'd like to see a mention that our SDK is compatible with Svelte, and that SvelteKit is just a Svelte framework used for this example.

I suggest submitting it as a PR next time, so it's easier to review 👍

from community-content.

nnennandukwe avatar nnennandukwe commented on June 28, 2024 1

This looks like a great outline structure. 👍

from community-content.

nunogois avatar nunogois commented on June 28, 2024 1

I noticed a few things with your example repo:

  • "This is an example of using SvelteKit with Unleash Client SDK." - Maybe we should be specific and mention that this is the Svelte SDK instead
  • "If you're country's" - typo, should be "If your country's"
  • Would be nice to get rid of the 404 for the favicon when running the project, either by adding a favicon or adjusting the link

image

from community-content.

rishi-raj-jain avatar rishi-raj-jain commented on June 28, 2024 1

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: Unleash/unleash#5246 (comment)

from community-content.

nunogois avatar nunogois commented on June 28, 2024 1

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:

  • In the section where you describe the tutorial and what we'll be doing, I think it would be cool to add some screenshots of your example app
  • Set up Unleash: We'll need an Unleash instance running to be able to follow the rest of your guide, so maybe it should be the first step after the requirements.
  • Check out the example app: For users that just want to play around with the example app and Unleash, we explain how they can clone it to a new folder, separate from Unleash, install its dependencies, and run it. We can also explain a bit what it's supposed to do, how it works, etc.
  • Code step by step: For users that want to dive a bit deeper and understand the steps involved, we explain how they can create a new project on a separate folder and implement something like this themselves, like you already have.

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 ✅

from community-content.

nnennandukwe avatar nnennandukwe commented on June 28, 2024 1

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!

  • "In the feature flag's dashboard, click on Add strategy:" Would be good to mention to click 'add strategy' in the development environment, since there are two 'add strategy' buttons. one for development and one for production.
  • If you want them to test the flag locally, then letting them know to enable the development (switch the development toggle on) would be good once they've created their new flag
  • I agree with Nuno. In the "Set up Unleash" section, explicitly tell them to move out of the project repo before they clone unleash so they are operating in separate repos.
  • Would it possible to mention they'll need to create a frontend API token in Unleash to use in unleashConfig. We explain something like that here, for example: https://docs.getunleash.io/feature-flag-tutorials/react#3-create-enable-and-configure-a-feature-flag
  • In "Integrating Unleash in SvelteKit", maybe rename the section to something like "Install Unleash SvelteKit SDK into your project". And let them know they need to go back into their project's repo and install there, since they're switching back and forth between their project repo, Unleash repo, and Unleash instance. It could be confusing for them so clarity is best here. :)
  • "Pass the language as context in the Wrapper component:" I think being specific about the name of the component would make this easier to identify. Refer to the <FlagProvider> -> <Content> so they could easily search for it in their file and pass in {language}
  • I agree that showing something in the browser would be helpful. Even a console log of the flag data would help with a user verifying things are working once everything is fully set up.

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

from community-content.

rishi-raj-jain avatar rishi-raj-jain commented on June 28, 2024 1

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

from community-content.

rishi-raj-jain avatar rishi-raj-jain commented on June 28, 2024 1

Socials 👇🏻

from community-content.

rishi-raj-jain avatar rishi-raj-jain commented on June 28, 2024

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 [email protected]: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:

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

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.

from community-content.

rishi-raj-jain avatar rishi-raj-jain commented on June 28, 2024

@nunogois

This is such a super detailed feedback!

I've updated the code & the blog to reflect all the changes 🙏🏻

from community-content.

rishi-raj-jain avatar rishi-raj-jain commented on June 28, 2024

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

from community-content.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.