How to integrate Feature Flags in NestJS

Chavez HarrisChavez Harris
5 min read

Software development can be challenging, but releasing new features shouldn't be. A feature deployment process can be time-consuming and error-prone without a proper feature flagging system. To me, it should be a fundamental part of the developer's toolbox because it lowers the risk of bugs and complications.

How do Feature Flags function?

A feature flag serves as a proxy between a feature and a user. Feature flagging involves linking a feature to a feature flag. You can control the rendering of a feature by turning its flag on or off. Having this level of control allows software engineers to develop and deploy features efficiently and confidently.

Feature Flags in Nest

The concept of feature flagging is language agnostic and can be used in most programming languages and frameworks we're already accustomed to. Let's see how we can implement this in a NestJS application using ConfigCat's feature flag management software.

ConfigCat has a 10 minutes trainable interface and provides a dashboard for managing feature flags. Thanks to the user segmentation feature, we can target user segments based on custom attributes. Using this method, we can observe the effects of new features on users who have opted into our beta testing group while avoiding regular users and paying customers.

Sample application

To illustrate the concept, I've created a fictional auto dealership website using NestJS. Since Nest is considered a server-side framework, the frontend components were developed using Vue.js.

My focus here will not be on frontend development. The complete frontend can be found here.

Here's a short breakdown of the app:

On the home page of the application, just under the banner, I've added:

  • A newsletter subscription form - Let's consider this to be a pre-existing component of the site.
  • A fuel mileage calculator - The new feature to be rolled out.

Before diving in, let's review the following prerequisites:

Prerequisites

  • A code editor (eg. Visual Studio Code)
  • Node version 16 or higher
  • Basic NestJS and JavaScript knowledge

Developing the NestJS application

  • Launch your favorite code editor and terminal in your app's directory. If you do not have an existing app, I'll briefly cover the steps to get you started.

  • Install the Nest CLI and create a new Nest project with the following commands:

npm i -g @nestjs/cli
nest new nest_app

Select npm as the package manager when prompted and give the process a moment to complete.

  • Navigate to the app's directory and run the following command. Try accessing the app on http://localhost:3000/. You should see the "Hello World!" message.
npm run start
  • To use Nest with a Vue.js frontend, I've modified the main.ts file as follows:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors(); // New
  app.setGlobalPrefix('api'); // New
  await app.listen(3000);
}
bootstrap();

Creating a feature flag

To integrate feature flagging, we have to modify the app.controller.ts file. But first, let's create a feature flag.

  • Sign for a free ConfigCat account, then navigate to the dashboard and create a feature flag with the following data:
FieldValue
namecanShowMileageFeature
keycanshowmileagefeature

Snapshot of creating the feature flag

  • Click the button on the right of the screen as shown below to enable the feature flag.

Snapshot of turning on the feature flag

Integrating with ConfigCat

It is strongly recommended to use the ConfigCat Client as a Singleton object in production.

  • Because Nest is a server-side rendered framework, we'll need to install the SSR (Server-Side Rendered) version of the JavaScript SDK from ConfigCat. To do so, open a terminal and navigate to the root of the app and run the following command:
npm i configcat-js-ssr

This will install the required packages needed to connect our Nest app to ConfigCat.

  • Update the src/app.controller.ts file as shown below. I've added comments code snippets below to explain each part.
// Import ConfigCat
import * as configcat from "configcat-js-ssr";
import { IConfigCatClient } from 'configcat-common';
@Controller('travel')
export class AppController {
  constructor(private readonly appService: AppService) {
    // Initialize the ConfigCat client with your SDK key
    this.configCatClient = configcat.createClient("-VbaCFs0RUGAghJLdTal-g/ZRvIWKTu0k-ZXxhOiebpBQ");
  }
}
  @Get('mileage')
  async getMileageFeature(): Promise<Boolean> {
    // Create a variable to store the state of the feature flag from ConfigCat.
    // This variable will be automatically updated every 60 seconds by default.
    const canShowMileageFeature = await this.configCatClient.getValueAsync("canshowmileagefeature", false)

    if (canShowMileageFeature) {
      // When true is returned to the frontend, the Gas Mileage feature is rendered
      return true
    } else {
      // When false is returned to the frontend, the Gas Mileage feature is not rendered. Instead, the subscription form will be rendered.
      return false
    }
  }

  public configCatClient: IConfigCatClient
}

App demo

Snapshot of the sample app

  • Turn the feature flag off in the ConfigCat dashboard. The home page should now look like this:

Snapshot of turning off the feature flag

Snapshot of the sample app - feature flag turned off

By default, the ConfigCat client SDK pulls the status of the feature flag every 60 seconds. This eliminates the need to restart the app. ConfigCat also gives you the ability to increase or decrease this interval period -- more about that here.

Conclusion

The process of adding feature flags to your apps is fast, easy, and does not take much time. For development workflows with regular feature releases, a feature flagging workflow is ideal. Feature flag services are especially useful for canary releases, where experimentation is crucial and rollbacks can be performed easily via feature toggles.

You or your team can be up and running in no time thanks to the comprehensive ConfigCat documentation. A variety of other frameworks and languages are also supported. For a complete list of SDKs supported, please refer to this page.

Stay up-to-date with ConfigCat on Twitter, Facebook, LinkedIn, and GitHub.

0
Subscribe to my newsletter

Read articles from Chavez Harris directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Chavez Harris
Chavez Harris

Inspiration does exist, but it must find you writing code.