Using Feature Flags in a Remix Application

Remix, the React-based full-stack framework for building server-rendered applications, has been generating a lot of buzz lately, especially since it was open-sourced. Remix is a dedicated Server-Side Rendering (SSR) framework for building web applicati…


This content originally appeared on DEV Community and was authored by David Herbert💻🚀

Remix, the React-based full-stack framework for building server-rendered applications, has been generating a lot of buzz lately, especially since it was open-sourced. Remix is a dedicated Server-Side Rendering (SSR) framework for building web applications that are rendered on the server.

Feature Flag Basics

Fundamentally, a feature flag is nothing more than a simple variable that can be remotely set to true or false. It is mostly used as feature switches to toggle on/off a section of a piece of code, usually a functionality or feature that is wrapped in a conditional if statement that uses the feature flag's value for its logic.

Here's a generic code snippet that demonstrates how a feature flag works in its simplest form:

const theFeatureFlag = true

if (theFeatureFlag === true ) {
     // execute the code here i.e enable this functionality
          }

Rather than doing a risky all-out deployment or launch, feature flags allow you to slowly roll out features through user segmentation and easily decouple code from deployment, which can be extremely helpful in a production environment when used in continuous integration and continuous delivery cycle. They also have a lot of other use cases, outside of just these.

Building a Hacker News Trending Feed with Remix

To demonstrate how we can use feature flags in a Remix application, we will start by building a simple Remix app that pulls trending news stories from the popular Hacker News website using the unofficial Hacker News Search API on Algolia.

The idea is to create a news feed that displays the top 20 trending news and then proceed to wrap this feed functionality in a feature flag that is hosted on ConfigCat. Whenever the flag is toggled on, the user visiting the site is shown the top 20 trending news. When the flag is toggled off the user is unable to see this trending news feed.

Let’s get started!

Prerequisites

  • Basic knowledge of React and Remix.
  • Local installation of Node.js and NPM.
  • A ConfigCat account which will be used to create the feature flag. Register now – It’s free.

Initializing our Remix App for our Feature Flag

Here is the source code to the sample Remix app on GitHub if you want to follow along. We’ll start by quickly spinning up a working Remix demo app using the create remix command.

npx create-remix@latest

This would present us with an interactive welcome screen prompting us to select where and what should be included in our demo app. In the end, we’d be prompted to run npm install to install all of our dependencies.

Remix demo app for our feature flag
Now that we have a working demo Remix app, let’s proceed to build our Hacker News feed for our feature flag. We’ll start by creating a loader function in our Remix root component that runs on the server - this allows us to make API calls on the server before the app is rendered.

import styleURL from "~/styles/global.css";
import { useLoaderData } from "remix";

// Runs on the server - for api calls
export const loader = async () => {
  // fetch stories from HN
  const stories = await fetch(
    "https://hn.algolia.com/api/v1/search?tags=front_page"
  );
  const newsFeed = await stories.json();

  // return stories to App component
  return [newsFeed.hits];
};

We have successfully created a fetch request that pulls in the desired stories from Hacker News and returns it as an array of news stories. Next, we’ll proceed to create our actual HTML template where we will loop through this returned array and render the news as ordered list items.

export default function App() {
  // get access to the stories in the loader function created above
  const [newsFeed] = useLoaderData();

  return (
    <html lang='en'>
      <head>
        <meta charSet='UTF-8' />
        <meta http-equiv='X-UA-Compatible' content='IE=edge' />
        <meta name='viewport' content='width=device-width, initial-scale=1.0' />
        <link rel='stylesheet' href={styleURL} />
        <title>Demo Feature Flag</title>
      </head>

      <body>
        <div>
          <h1>Trending Hacker News Feed</h1>

          <ol>
            {newsFeed.map((story) => (
              <li key={story.id}>
                <a href={story.url}>{story.title}</a>
              </li>
            ))}
          </ol>

        </div>
      </body>
    </html>
  );
}

With that we should now have a working Hacker News Feed that renders the top 20 trending news stories as shown below.

Remix Hacker News Feed clone

Setting up a Feature Flag on ConfigCat's Dashboard

  1. To create a new feature flag, sign in to your ConfigCat dashboard. In the upper-left corner of your dashboard you can create a new config file or use the default ‘main’ config.
    ConfigCat feature flag setup dashboard

  2. After which, select the ‘Add Feature Flag’ option that allows you create new feature switches and give your flag a name and key value that would be used to access the flag in your application code.

Add New Feature Flag or feature toggle

  1. Lastly, copy the SDK key as it would be needed to connect your application to the dashboard.

Feature flag SDK Key

There are also targeting options to configure how to serve the feature flag through user segmentation, but to keep things simple we will only be using the default settings - which is to target all.

Initializing the Feature Flag Service SDK in Our Remix App

Feature flag management solutions rely on SDKs. The SDK is installed into your application code where it communicates with the feature flag management service to determine what state the feature flags are in and checks the configuration rules for how they are to be served, i.e what users to target. Additionally, some companies' SDKs like that of ConfigCat are generally open source and safe, but this is not the same for all companies.

To use the ConfigCat Feature Flagging service, we have to install the ConfigCat SSR Package in our application via NPM.

npm i configcat-js-ssr

We will now import the package into our root App component and then initialize it in our loader function with the SDK key that we copied earlier. This would connect our Remix application to our ConfigCat dashboard.

So, let’s refactor our initial loader function to include just that.

import styleURL from "~/styles/global.css";
import { useLoaderData } from "remix";
import * as configCat from "configcat-js-ssr";

// Runs on the server - for api calls
export const loader = async () => {

  // Connect to your ConfigCat's dashboard
  const configCatClient = configCat.createClient(
    "fK7ZCApWbkaDu14njPKZQw/vBw-jxALN0eiWNilfwboGA"
  );

  // Check and store status of feature flag
  const newsFeedFlag = await configCatClient.getValueAsync(
    "newsfeedfeatureflag",
    false
  );

  // Fetch stories from Hacker News
  const stories = await fetch(
    "https://hn.algolia.com/api/v1/search?tags=front_page"
  );
  const newsFeed = await stories.json();

  // return stories and status of the feature flag to App component
  return [newsFeed.hits, newsFeedFlag];
};

Controlling the News Feed Functionality with a Feature Flag

Now that we have access to the status of the feature flag in our ConfigCat dashboard, let’s refactor our initial HTML template using a ternary operator to condition whether the news feed is visible or not, depending on the state of the feature flag.

export default function App() {
   // Get access to the stories and state of feature flag in the loader function created above
  const [newsFeed, newsFeedFlag] = useLoaderData();

  return (
    <html lang='en'>
      <head>
        <meta charset='UTF-8' />
        <meta http-equiv='X-UA-Compatible' content='IE=edge' />
        <meta name='viewport' content='width=device-width, initial-scale=1.0' />
        <link rel='stylesheet' href={styleURL} />
        <title>Demo Feature Flag</title>
      </head>

      <body>
        <div>
          <h1>Trending Hacker News Feed</h1>

          {newsFeedFlag ? (
            <ol>
              {newsFeed.map((story) => (
                <li key={story.id}>
                  <a href={story.url}>{story.title}</a>
                </li>
              ))}
            </ol>

          ) : (
            <h2>Ops! News Feed unavailable</h2>
          )}
        </div>
      </body>
    </html>
  );
}

We can now control our news feed feature from our ConfigCat dashboard using feature toggles. When the feature flag is toggled off, the news feed would be disabled and the user won’t have access to it as shown below.

Disabled Feature flag or feature toggle

But when the feature is toggled back on, the user is given access to the news feed.

Feature flag enabled

The Remix sample app on GitHub

Key Takeaways

As seen in the Remix application built above, feature flags make it rather easy to remotely control or release features in your application. With feature flags developers, testers, and IT personnel can basically turn on or off certain functionality and perform targeted releases through user segmentation without affecting the existing application infrastructure.

However, it is not your team's core competency to build a feature flagging system as it may distract them from their main development process. The need for a feature flag management service is therefore essential as feature flags help you take control of your future releases.

For more, you can follow ConfigCat on Facebook, Twitter and LinkedIn.


This content originally appeared on DEV Community and was authored by David Herbert💻🚀


Print Share Comment Cite Upload Translate Updates
APA

David Herbert💻🚀 | Sciencx (2022-04-05T06:36:52+00:00) Using Feature Flags in a Remix Application. Retrieved from https://www.scien.cx/2022/04/05/using-feature-flags-in-a-remix-application/

MLA
" » Using Feature Flags in a Remix Application." David Herbert💻🚀 | Sciencx - Tuesday April 5, 2022, https://www.scien.cx/2022/04/05/using-feature-flags-in-a-remix-application/
HARVARD
David Herbert💻🚀 | Sciencx Tuesday April 5, 2022 » Using Feature Flags in a Remix Application., viewed ,<https://www.scien.cx/2022/04/05/using-feature-flags-in-a-remix-application/>
VANCOUVER
David Herbert💻🚀 | Sciencx - » Using Feature Flags in a Remix Application. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/04/05/using-feature-flags-in-a-remix-application/
CHICAGO
" » Using Feature Flags in a Remix Application." David Herbert💻🚀 | Sciencx - Accessed . https://www.scien.cx/2022/04/05/using-feature-flags-in-a-remix-application/
IEEE
" » Using Feature Flags in a Remix Application." David Herbert💻🚀 | Sciencx [Online]. Available: https://www.scien.cx/2022/04/05/using-feature-flags-in-a-remix-application/. [Accessed: ]
rf:citation
» Using Feature Flags in a Remix Application | David Herbert💻🚀 | Sciencx | https://www.scien.cx/2022/04/05/using-feature-flags-in-a-remix-application/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.