Product
|
Cloud costs
|
released
July 14, 2021
|
3
min read
|

Implement Your First Feature Flag

Updated
10/4/2023

Feature Flags are an important part of delivering on Progressive Delivery goals. Though, having logic to enable or disable certain code blocks/methods is nothing new; conditional statements have been around for several decades. Though at scale, trying to advance the goals of Progressive Delivery without a management solution can be complex.

In this example, by leveraging the Harness Platform and an example project, you can gauge the level of effort to start using Harness Feature Flags and potentially look to scale this across your team and organization for unified feature flag management.

Getting Started – Your First Feature Flag

In this example, there are a few moving pieces. Some you might already have a solution or application for, so feel free to use your own. If you do not have an IDE (integrated development environment), this example will walk you through soup to nuts. This example will require a GitHub Account, IDE, Harness Account, and the ability to run an NPM Install in your local or remote environment.

VS Code

Microsoft’s VS Code is an excellent IDE to get started on. You can follow the installation instructions on the Microsoft site. Once installed, you can save your Workspace [view]. You will be presented with a blank Explorer.

Blank Explorer

GitHub

Once signed in to your GitHub or your SCM tool of choice, we will be using Google Pay’s React Store as a base application. You can Fork [copy] this repository/application into your own account so you can freely edit.

Once forked in, you can import into VS Code or GIT Clone to your machine/IDE of choice. Click “Code” to see the different options. For now, the HTTPS method is fine.

NodeJS/NPM

The sample application leverages React and NodeJS to power the application. If leveraging a Mac, an easy way to install NodeJS is to use Homebrew. NPM is the package manager for the NodeJS ecosystem, so you can install both by typing in brew install npm.

For Windows, you can also use Chocolatey to install.  

Run the Base Version of the App

Now you are ready to run the base version of the application. You can enter the HTTPS address of the GitHub repository directly into VS Code, e.g. Clone Repository.

Hit enter and select a folder to store the contents. Once a folder is selected, click “Select Repository Location.”

Once the import is complete, you can head to the terminal in VSCode and run the first NPM Install, e.g. “npm install” in the terminal to get the dependencies resolved. Depending on the security settings on your Mac, you might have to grant VS Code access to files and directories.

Per the documentation, you can bootstrap a local/development version of the application by running NPM Start. In the terminal, run npm start. On your local machine again, you might have to allow connectivity. You can access the application on localhost or your remote IP over port 3000.

Once started:

We are now ready to flag a piece of functionality.

Ready Your Application for Feature Flags

Creating and executing a Feature Flag for the React app is pretty straightforward. Depending on the language, Feature Flags can require the use of an SDK (software development kit), which is installed as a dependency. Harness has several SDKs available and several more on the roadmap. Since this example application is React (non-mobile), we can leverage the JS Feature Flag SDK.

Add the SDK Dependency

There are a few ways to add the React SDK dependency. The easiest way in the example application is to just include the dependency in the package.json, which is “@harnessio/ff-javascript-client-sdk”: “^1.4.4”. Navigate to the package.json and add the JS Client as a dependency.

"@harnessio/ff-javascript-client-sdk": "^1.4.4",

Make sure to Save. You can re-run NPM Install again if you want to here or you can start to modify some of the JS. If your local server is still running in the terminal, you can use “ctrl+c” to stop it.

With the dependency out of the way, now it is time to head to the Harness Platform and create your first Feature Flag project.

Your First Harness Feature Flag

Feature Flags is part of the Next Generation of the Harness Platform. If this is your first time leveraging the Next Generation (NG) platform, navigation is a breeze. The first item to create is a new Project.

Home -> Projects + Project

Follow the prompts. In this example, we are creating a Project called “Your First Feature Flag.”

Once inside your Project, once entitled you can navigate to the Feature Flags section on the left-hand navigation and create an Environment, Key, and Flag.

The first step is to create an Environment by clicking on Environments then Create Environment. In this example, I named my environment “localmbp” for my local machine.

Once you click Create, the next step would be to create an SDK Key.

Your First Feature Flag – > Feature Flags -> Environments -> Settings + Add Key

For this instance, we can make a Client SDK Key. You can give a generic name such as jsaccesskey.

Click Create. Though Keys are only viewable once, make sure to copy down the key.

In this example, our key will be 9f6e0602-6c45-4a50-8826-1b5a1b250453.

The next step is to create a Flag.

Your First Feature Flag -> Feature Flags -> + Flag

Add a Boolean Flag:

Select Boolean, then give the flag a name such as abooleanflag.

Click Next.

The default settings are fine. Basically, if the Flag is on, send back True. If the Flag is off, send back False. The easiest on/off switch there is.

Click Save and Close and your Flag is ready to be used.

Now you are ready to wire in the calls and can turn the Flag ON and OFF on the platform. Leave the Flag off for now.

Source Code Wiring

There needs to be some wiring at the source code level so the application can communicate back to the Feature Flag Platform.

SDK Initialization

A good spot to initialize the client in this application would be the App Landing itself, e.g. App.tsx, since the header is across all of the pages in this application. The code for the client is located here in the documentation and has an example implementation on GitHub. Per the linting rules in the example project (they are quite strict), you can disable those for an easier experience.

Header.tsx is located at react-store/src/App.tsx.

You can disable the linting rules on the App.tsx by adding the //@ts-nocheck annotation to the top of the file.

// @ts-nocheck

The next step would be to add the import for the SDK.

import { Event, initialize } from '@harnessio/ff-javascript-client-sdk';

You’ll want to initialize the SDK once imported. You will need your SDK Key and Flag Identifier. One particular way of wiring the SDK initialization is to use a React Effect Hook. The Identifier is available in the UI under the Flag Name. In this case, “abooleanflag” is the Identifier.

The below code will leverage a React Effect Hook (e.g. useEffect) to initialize the SDK, wire to the platform, and listen for events (e.g. changes in the Flags).

You can copy and paste the below block and place it in the App() function. Make sure to update your Client SDK Key and identifier.

const [featureFlags, setFeatureFlags] = useState({}); useEffect(() => {   const cf = initialize(     'your-client-sdk-key',     {       identifier: 'your-identifier',       attributes: {         lastUpdated: Date(),         host: window.location.href,       },     },     {       baseUrl: 'https://config.ff.harness.io/api/1.0',       eventUrl: 'https://events.ff.harness.io/api/1.0',     },   );   cf.on(Event.READY, flags => {     setFeatureFlags(flags);     console.log(flags);   });   cf.on(Event.CHANGED, flagInfo => {     console.log(flagInfo);     if (flagInfo.deleted) {       setFeatureFlags(currentFeatureFlags => {         delete currentFeatureFlags[flagInfo.flag];         return { ...currentFeatureFlags };       });     } else {       setFeatureFlags(currentFeatureFlags => ({ ...currentFeatureFlags, [flagInfo.flag]: flagInfo.value }));     }   });   return () => {     cf?.close();   }; }, []);

With the SDK Client and event wirings in place, you are now ready to start wrapping some code with Feature Flag evaluations.

Feature Flags Evaluation

The art of the possible is great with Feature Flags. For a concrete example, we can have a little fun with the UI. For example, we can swap out some CSS to allow for the title on the top to either be centered default or to the left.

With the let expression, we can evaluate if “abooleanflag” is true. If so, we can assign the CSS class to either “App.Left” or just “App” for default.

A good place to add this code is before the return.

let className = featureFlags.abooleanflag ? 'App.Left' : 'App';

In the generation section of App.tsx where the <div> class is set, you can update that to be a variable e,g className vs the static “App” class.

<div className={className}>

Lastly, you can add the updated CSS into App.CSS.

Your First Feature Flag: CSS

.App.Left { text-align: left;}

Executing Your First Feature Flag

After the code modifications, it is time to see Feature Flags in action. You might need to restart the local NPM start by hitting “ctrl+c” in the VSCode terminal and running NPM Start again.

Running NPM Start will bring up a pre-built local copy on your machine over port 3000.

Your First Feature Flag: Terminal

You can run a built version if you choose too which is served over port 5000 by running a npm build, install, and serve.

npm run buildnpm install -g serveserve -s build

Back in the Harness Feature Flag platform, make sure the Flag is turned off.

Your First Feature Flag -> Feature Flags -> abooleanflag

Your First Feature Flag: Turn Off Flag

In the React Store, you will see the title “Shop” centered.

Your First Feature Flag: Shop

Now you can turn the Flag on and see the title move. Make sure to click Save in the Harness Feature Flag Platform.

Your First Feature Flag: Boolean Flag

Once saved, the title will be on the left.

Your First Feature Flag: It's Live!

Now you have a functioning Feature Flag! Back in the Harness Platform, you can look at the metrics for your Flag.

Your First Feature Flag: Metrics

Congratulations on running through the example! If you are having some trouble, there are two issues that can pop up during this example.

Troubleshooting

Like any code-based example, there can be a little troubleshooting that needs to take place. What we observed with running this example locally on our machines can provide some hints.

Server Sent Events (SSEs) Blocked

Certain enterprise intrusion detection platforms will block SSEs on your local machine if hosting the sample application on your local machine. The Harness SDK, if invocated, uses SSEs to monitor for changes in the Flags. You would need to get an exception from your networking team to run the Node instance on your local machine.  

Linting/Prettier Suppression

If using a Windows PC or even copy and paste, you will potentially run into a linting issue based on the new line returns, etc. You can disable the Prettier plugin in the eslintrc config by adding the below rule. The manifestation of this would be errors from prettier/prettier in the console or browser.

Your First Feature Flag: Prettier Plugin

   "prettier/prettier": 0,

Hopefully those issues do not manifest for you.

Only the Beginning With Feature Flags

Moving pieces of your UI around for various audience segments is just the tip of the iceberg with Harness Feature Flags. By using a management platform, you can delve into the art of the possible. Stay tuned as the Feature Flag Platform continues to evolve and bring on new SDKs and functionality for software release. Follow along with us in the documentation and get started today!

Cheers,

-Ravi

Sign up now

Sign up for our free plan, start building and deploying with Harness, take your software delivery to the next level.

Get a demo

Sign up for a free 14 day trial and take your software development to the next level

Documentation

Learn intelligent software delivery at your own pace. Step-by-step tutorials, videos, and reference docs to help you deliver customer happiness.

Case studies

Learn intelligent software delivery at your own pace. Step-by-step tutorials, videos, and reference docs to help you deliver customer happiness.

We want to hear from you

Enjoyed reading this blog post or have questions or feedback?
Share your thoughts by creating a new topic in the Harness community forum.

Sign up for our monthly newsletter

Subscribe to our newsletter to receive the latest Harness content in your inbox every month.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Feature Flags