Skip to main content

How to integrate Feature Flags in NestJS

· 6 min read
Chavez Harris

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.

Cover Photo

How do Feature Flags function?

Feature flags are a piece of code that conditionally hides and displays functionality. 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

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

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

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

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

dashboard

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

Cover Photo

Integrating with ConfigCat

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

  1. Because Nest is a server-side framework, we'll need to install ConfigCat's Node SDK. To do so, open a terminal and navigate to the root of the app and run the following command. This will install the required packages needed to connect our Nest app to ConfigCat.
npm i configcat-node
  1. Since it is recommended to use the ConfigCat client as a singleton, I'll create a custom service for it that we can use to check the status of the feature flag. Create a file in the src directory called configcat.service.ts with the following content:
import { Injectable } from '@nestjs/common';

// Import the ConfigCat client SDK
const configcat = require("configcat-node");

@Injectable()
export class ConfigCatService {
private readonly configcatclient = configcat.createClient(
'YOUR_CONFIGCAT_SDK_KEY',
);

getFeatureStatus() {
return this.configcatclient.getValueAsync('canshowmileagefeature', false);
}
}
  1. Update the src/app.controller.ts file as shown below. I've added comments to explain each part.
// Import the custom ConfigCat service
import { ConfigCatService } from './configcat.service';
@Controller('travel')
export class AppController {
constructor(
private readonly appService: AppService,
private configCatService: ConfigCatService,
) {}
}
  @Get('mileage')
async getMileageFeature(): Promise<boolean> {
// Create a constant to store the state of the feature flag returned by the custom ConfigCat service.
// This will be automatically updated every 60 seconds by default.
const canShowMileageFeature =
await this.configCatService.getFeatureStatus();

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;
}
}

You can find the complete code here.

App demo

  1. Start the app and navigate to http://localhost:3000/ as shown below:

Screenshot of the sample app

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

Screenshot of ConfigCat&#39;s dashboard

Screenshot of the sample app

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.