DEV Community

Cover image for How to use JavaScript feature toggles to deploy safely [React.js example with Dev.to App]
Ilya Azovtsev
Ilya Azovtsev

Posted on • Originally published at flagsmith.com

How to use JavaScript feature toggles to deploy safely [React.js example with Dev.to App]

Feature flags aka Feature toggles in any language significantly reduce the blast radius of a release if anything goes wrong. Javascript feature flags are no exception. We already shared the guide on how to use feature flags in Node.js. In this post, you will learn how to use javascript feature toggles in a React.js application to deploy a small feature safely to your users.

Let’s get started!

Prerequisites

Prior to diving deeper into the code and JavaScript feature toggles, below are some of the good to have requisites:

  1. Some knowledge of Javascript and React.js would be essential
  2. Knowing how Node.js and Yarn work are required, knowledge of adding new packages with Yarn is also needed
  3. A Flagsmith account will be used to create the feature flag. Register now – It’s free. Flagsmith is the open-source product - check out Github.

We will jump right into the code part now, brace yourself.

Example: JavaScript feature flag with React.js Dev.to app

We will build a simple React.js app that will list the latest articles from Dev.to. Dev is a community of software developers getting together to help one another out and this is the place where you read this article 😅. It is an amazing community where anyone can publish technical content without any editorial process. Based on Forem it has a handy API and we are going to use the articles API to list the latest articles in a light React.js application.

To create the React.js application using create react app, we will run the following command:

npx create-react-app devto-react 
Enter fullscreen mode Exit fullscreen mode

It will render output as follows when the setup is complete:
Image description

Next, we will quickly run the React.js boilerplate application to see if it is running with:

cd devto-react

yarn start
Enter fullscreen mode Exit fullscreen mode

It will start the development server and open the default browser at http://localhost:3000 which looks like:

Image description

Hurray! Our skeleton React app created by Create React App for the JavaScript feature toggles tutorial is running. We will change the code to call the Dev.to API next.

And will change the src/App.js file to look like below:

import React, { useState, useEffect } from 'react';
import './App.css';
function App() {
  const [articles, setArticles] = useState([]);
  const [message, setMessage] = useState('loading…');
  useEffect(() => {
    async function fetchArticles () {
      try {
        const data = await (await fetch('https://dev.to/api/articles/latest')).json();
        setArticles(data)
        const message = data.length ? "" : 'No articles found';
        setMessage(message);
      } catch (err) {
        console.log('err: ${err.message}', err);
        setMessage('could not fetch articles');
      }
    }
    fetchArticles()
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <h2>Latest Dev.to articles</h2>
        {message}
        <div className="articles">
          <ul>
          {Array.isArray(articles) && articles.map(
            article => article.url && <li><a href={article.url} target="_blank" rel="noreferrer">{article.title}</a> – by {article.user.name}</li>
          )}
          </ul>
        </div>
      </header>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

We are using the React useState hook to define two variables articles and the message. Then using the effect hook we are calling the Dev.to API in the fetchArticles function. The articles fetched are being put into the articles variable. In case of any error a message of No articles found is put into the message variable.

Below, in the return section, we are looping through all the fetched articles and showing the title of the article with a link to it and the name of the user who has posted the articles.

Consequently, we will change the src/App.css to have the following contents

.App-header {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  font-size: calc(10px + 2vmin);
}

.App-header h2 {
  text-align: center;
}

.App-link {
  color: #61dafb;
}
Enter fullscreen mode Exit fullscreen mode

The CSS has been simplified to show the list of articles, removing the unneeded styles for the logo and the background. Text color and text alignment have been reset too.

The focus of this tutorial is to help you learn how to do React feature flags with Flagsmith. When we run it with yarn start after making the above changes, the application looks like below at this point:

Image description

For the scope of this guide, we will add the reading time in minutes for the articles. As this small feature will be added with JavaScript feature toggles, it will be very easy to turn it on and off simply by flipping a flag within Flagsmith; no re-deployments are necessary. That is the power and convenience of feature flags, as deployment is not a release.

In the next section, we will set up the feature flag for our example within Flagsmith’s UI. Then we will add Flagsmith’s JavaScript SDK, available on NPM, to our project. After that, we will add some code to implement the simple flag to show or hide the reading time for the Dev articles.

Setup Flagsmith to have Feature Flags

Flagsmith is the open-source product - check out Github.

To create JavaScript feature toggles to show or hide the reading time for articles we will first create a project on Flagsmith. To create the project we will click the “Create Project” button after logging in:

Image description

I have named the project Dev-React, and then, we will reach the project page like below:

Image description

We will scroll down the page and create a new feature flag called show_reading_time as seen below:

Image description

Now we have created a new feature flag called show_reading_time and enabled it. It would be created in both development and production environments in Flagsmith. Next, we will install the flagsmith NPM library and use it in the React.js app for our JavaScript feature flags tutorial.

Install and use Flagsmith JavaScript client

If you like what we do, check out Flagsmith the open-source product - check out Github.

We have created the feature flag in Flagsmith on the UI, now it is time to use it in the Dev React app. To do this for our JavaScript feature flags tutorial, we will first get the Flagsmith JavaScript client from NPM running the following:

yarn add flagsmith
Enter fullscreen mode Exit fullscreen mode

After the flagsmith client is installed we will change the code in src/App.js. First, we will add the following line on line 2 to import Flagsmith library into the app:

import flagsmith from 'flagsmith';
Enter fullscreen mode Exit fullscreen mode

Subsequently, we will add the following at line 8 to initialize the showReadingTime variable which will be false by default:

const [showReadingTime, setShowReadingTime] = useState(false);
Enter fullscreen mode Exit fullscreen mode

Then we will add the code below in useEffect function below fetchArticles call at line 22 as follows:

flagsmith.init({
    environmentID:"VKE5KnX8xXZuztTDGbcvBU",
    cacheFlags: true,
    enableAnalytics: true,
    onChange: (oldFlags, params) => {
    setShowReadingTime(flagsmith.hasFeature('show_reading_time'));
    }
  });
Enter fullscreen mode Exit fullscreen mode

You can get the environment ID from the “Initialize your code” section of the feature flag page as seen below:

Image description

Consequently add the following code where you see the looping through articles towards line 40:

<ul>
          {Array.isArray(articles) && articles.map(
            article => article.url && <li><a href={article.url} target="_blank" rel="noreferrer">{article.title}</a> – by {article.user.name} {showReadingTime ? '(Around ${article.reading_time_minutes} minute${article.reading_time_minutes > 1 ? "s": ""} read)' : ""}</li>
          )}
</ul>
Enter fullscreen mode Exit fullscreen mode

We have first imported Flagsmith’s JavaScript client, then set the showReadingTime on useEffect so that it is only called once on page load. Then when we render the articles we check if the reading time should be shown and then we print the reading time else we print the empty string. Next up we will see the changes in action.

Test JavaScript feature toggles changes

At this point if we again start the app it will show something like the below:

Image description

Great! We can see the reading time of the articles. Now if we would like to turn off showing the reading time, it is very easy. We can just go to the Flagsmith interface and turn the feature off like below:

Image description

After we hit “Confirm Changes” and the flag is off, if we come back and refresh the Dev React app page used for our example we will not see the reading times anymore as follows:

Image description

Wasn’t that easy? You can deploy the app and change the environment ID to be production for your production environment. In the next step, we will deploy the react application to Surge.

Deploy React App to Surge.sh (React Feature Flag)

We have run the application locally, so to deploy it to a more production-like environment we will use Surge.sh. It is a very easy platform to deploy our front-end application. To deploy our React application to surge first we will replace the key from development to production one. To do this we will go to the “Production” environment and then click “Initialising your project” under the features section as seen below:

Image description

We had done a similar thing for the development environment, as we want to deploy to a production-like environment we are replacing the environment ID to be of production. We will copy the environment id and replace it on line 23 of src/App.js which will look like below after the change:

flagsmith.init({
    environmentID:"BLPF23hJZ4ekaYV48epC55",
    cacheFlags: true,
    enableAnalytics: true,
    onChange: (oldFlags, params) => {
     setShowReadingTime(flagsmith.hasFeature('show_reading_time'));
    }
  });
Enter fullscreen mode Exit fullscreen mode

To deploy our Dev.to React app to surge we will run the following commands:

yarn build
Enter fullscreen mode Exit fullscreen mode

It will give the following output:

Image description

It will also create a build folder with the output of the build process which has the index.html file and other static assets.

To install the Surge command line we will run the following:

npm i -g surge
Enter fullscreen mode Exit fullscreen mode

Consequently, we will go into the build folder and deploy the built app with:

cd build
surge
Enter fullscreen mode Exit fullscreen mode

After that type in your email and a password. Then it will find your current working directory as the project. Then if you want, change the subdomain, I have used devto-react.surge.sh else use the random subdomain it provides. The hit enter and in a couple of seconds your app will be deployed to Surge over a CDN as seen below:

Image description

Pretty neat! Below is how the app looks on Surge.sh with the toggle for reading time “on” for Javascript feature flag, taken from the “production” environment:

Image description

You can try it out too at https://devto-react.surge.sh. You will get an email to verify your email address, if you are interested in Surge do check out their help section. In the following part, we will look at the next steps.

Next Steps

Implementing flags in JavaScript is a pretty easy task with amazing benefits. You can use the same Flagsmith JavaScript client in any frontend application ranging from vanilla JavaScript to Jquery to even Angular or Vue.js applications. It is also possible to use the SDK from a CDN with the following code:

<script src="https://cdn.jsdelivr.net/npm/flagsmith/index.js"></script>
Enter fullscreen mode Exit fullscreen mode

The main concept here is to deploy the feature safely, if there is an issue we should be able to turn it off in seconds, not minutes or hours. That is easily possible with feature flags on an open-source platform like Flagsmith or with the free plan. The feature can be turned on and off with a couple of clicks, not with a deployment process. That adds unprecedented power and flexibility to the software engineering teams. The safety of feature release is another desirable by-product of the whole process. By the way, you definitely need to check 5 best practices for Feature Flags.

Conclusion

We just saw how to implement JavaScript feature toggles on a simple React.js app that calls an API to show the latest Dev articles. This idea can be easily implemented in any frontend JavaScript application. Feature release can be done safely with high confidence and low time to turn on or off the released feature without the need to deploy any new code.

P.S. the original article was published here

Top comments (0)