How to integrate Feature Flags in NestJS
Tags: nestjs, featureflag, configcat, javascript
Published: 2022-08-20 01:35:00

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](https://configcat.com/).

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](https://github.com/configcat-labs/feature-flags-in-nestjs-sample) 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](https://github.com/configcat-labs/feature-flags-in-nestjs-sample/tree/master/client).

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:

```bash
npm i -g @nestjs/cli
```

```bash
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/](http://localhost:3000/). You should see the "Hello World!" message.

```bash
npm run start
```

- To use Nest with a Vue.js frontend, I've modified the **main.ts** file as follows:

```js
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](https://app.configcat.com/signup?returnUrl=%2F), then navigate to the dashboard and create a feature flag with the following data:

| Field      | Value |
| ----------- | ----------- |
| **name**     | canShowMileageFeature |
| **key**   | canshowmileagefeature |


![Snapshot of creating the feature flag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8zifog8nge6aiamacyup.png)

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

![Snapshot of turning on the feature flag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1req702wlx7v11w7lzgm.png)

## Integrating with ConfigCat

> It is strongly recommended to use the ConfigCat Client as a [Singleton](https://en.wikipedia.org/wiki/Singleton_pattern) object in production.

- Because Nest is a [server-side rendered framework](https://developer.mozilla.org/en-US/docs/Learn/Server-side/First_steps/Web_frameworks), 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:

```bash
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**](https://github.com/configcat-labs/feature-flags-in-nestjs-sample/blob/master/src/app.controller.ts) file as shown below. I've added comments code snippets below to explain each part.

```js
// Import ConfigCat
import * as configcat from "configcat-js-ssr";
import { IConfigCatClient } from 'configcat-common';
```

```js
@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");
  }
}
```

```js
  @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

- Start the app and navigate to [http://localhost:3000/](http://localhost:3000/) as shown below:


![Screenshot of the sample app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6f21zatb761gditm6ne6.png)


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

![Snapshot of turning off the feature flag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w985t8drxvkc4tbanlx7.png)

![Snapshot of sample app - feature flag turned off](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w3kmitq3dvgdbb6urwt3.png)

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](https://configcat.com/docs/sdk-reference/js-ssr/#manual-polling).

## 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](https://configcat.com/docs/sdk-reference/overview).

Stay up-to-date with ConfigCat on [Twitter](https://twitter.com/configcat), [Facebook](https://www.facebook.com/configcat), [LinkedIn](https://www.linkedin.com/company/configcat/), and [GitHub](https://github.com/configcat).