With feature flags (also referred to as feature toggles), we can modify our application’s behavior without changing the code. In this article, we explain the purpose of feature flags. We also show how to implement them ourselves and discuss the pros and cons.
You can find the code from this article in this repository.
The idea behind feature flags
Thanks to feature flags, we can switch a certain functionality on and off during runtime without the need to deploy any new code.
1async register(@Body() registrationData: RegisterDto) {
2 const user = await this.authenticationService.register(registrationData);
3 const isEmailConfirmationEnabled = await this.featureFlagsService.isEnabled('email-confirmation');
4 if (isEmailConfirmationEnabled) {
5 await this.emailConfirmationService.sendVerificationLink(
6 registrationData.email,
7 );
8 }
9 return user;
10}A feature flag, at its core, is a boolean value that we can toggle and use in if statements.
Benefits of feature flags
One of the main benefits of feature flags is that merging our changes into the master branch does not necessarily mean delivering the new feature to our users. Therefore, we get a lot of control over our application.
For example, feature flags are part of the Trunk Based Development practice, where we merge our code to the master branch very often. Since merging does not mean exposing the new feature to the users, we can merge features we haven’t finished. Thanks to that, the new feature can undergo the code review process in chunks instead of dumping a lot of code in a single pull request. The above can make it significantly easier for our teammates to review our new code.
Also, feature flags can help us minimize risks associated with deployments. If the QA team notices that the latest changes don’t work as expected in the production environment, reverting them is as easy as switching the toggle. Besides the QA team, we can also notice the issue through a monitoring system we have in place. A good example would be a sudden spike in the response time of some endpoints in our API.
Besides the above, we could build a more sophisticated feature flags system or use a third-party tool with functionalities like A/B testing. With that, we can present two versions of our application to users and determine which one they like the most.
Drawbacks of feature flags
While feature flags can benefit our application, they are not a perfect solution. They add complexity to our code that can make it harder to understand. But, what’s even worse, they create a lot of various versions of our application that, ideally, should be tested separately. For example, if we have five feature flags, it gives us 32 possible combinations.
There are two possible values for each of the five feature flags, and 25 equals 32. This would be even more complicated if we would have feature flags that can have values other than booleans.
Until we test each of them separately, we can’t be entirely sure if not a single one of the combinations has an unexpected side effect. Five feature flags might seem like not a lot, but manually testing 32 separate versions of our application is probably unrealistic. It would be reasonable only to verify the combinations we expect to happen in production, but that requires that we understand the project and the business domain very well. The more flags we have, the more difficult it is to verify.
Because of that, feature flags need to be short-lived. Although it is easy to add a feature flag, it can cause us more and more effort to maintain it the longer we keep it. Therefore, we should retire the feature flag once we know that a particular feature works correctly.
Having feature flags can encourage us to merge features that are not yet finished because they are hidden behind a feature flag. We need to be very careful, though, because there is a chance that a feature might leak out by accident if not encapsulated correctly. Having to test that adds even more complexity to testing.
Implementing feature flags with NestJS
We probably want different values for feature flags in different environments, for example, in staging and production. We would also like to change the feature flags without modifying the codebase and deploying.
The most straightforward way of doing the above is storing our feature flags in a database. First, let’s define an entity for our feature flag.
1import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
2
3@Entity()
4class FeatureFlag {
5 @PrimaryGeneratedColumn('identity', {
6 generatedIdentity: 'ALWAYS',
7 })
8 id: number;
9
10 @Column({ unique: true })
11 name: string;
12
13 @Column()
14 isEnabled: boolean;
15}
16
17export default FeatureFlag;If you want to know more about identity columns, check out Serial type versus identity columns in PostgreSQL and TypeORM
Adding, modifying, and removing feature flags is relatively straightforward. We can fit all of it into a simple service.
1import {
2 HttpException,
3 HttpStatus,
4 Injectable,
5 NotFoundException,
6} from '@nestjs/common';
7import FeatureFlag from './featureFlag.entity';
8import { InjectRepository } from '@nestjs/typeorm';
9import { Repository } from 'typeorm';
10import CreateFeatureFlagDto from './dto/createFeatureFlag.dto';
11import UpdateFeatureFlagDto from './dto/updateFeatureFlag.dto';
12import PostgresErrorCode from '../database/postgresErrorCode.enum';
13
14@Injectable()
15export default class FeatureFlagsService {
16 constructor(
17 @InjectRepository(FeatureFlag)
18 private featureFlagsRepository: Repository<FeatureFlag>,
19 ) {}
20
21 getAll() {
22 return this.featureFlagsRepository.find();
23 }
24
25 getByName(name: string) {
26 return this.featureFlagsRepository.findOneBy({ name });
27 }
28
29 async create(featureFlag: CreateFeatureFlagDto) {
30 try {
31 const newFlag = await this.featureFlagsRepository.create(featureFlag);
32 await this.featureFlagsRepository.save(newFlag);
33 return newFlag;
34 } catch (error) {
35 if (error?.code === PostgresErrorCode.UniqueViolation) {
36 throw new HttpException(
37 'Feature flag with that name already exists',
38 HttpStatus.BAD_REQUEST,
39 );
40 }
41 throw new HttpException(
42 'Something went wrong',
43 HttpStatus.INTERNAL_SERVER_ERROR,
44 );
45 }
46 }
47
48 async update(id: number, featureFlag: UpdateFeatureFlagDto) {
49 try {
50 await this.featureFlagsRepository.update(id, featureFlag);
51 } catch (error) {
52 if (error?.code === PostgresErrorCode.UniqueViolation) {
53 throw new HttpException(
54 'Feature flag with that name already exists',
55 HttpStatus.BAD_REQUEST,
56 );
57 }
58 throw new HttpException(
59 'Something went wrong',
60 HttpStatus.INTERNAL_SERVER_ERROR,
61 );
62 }
63 const updatedFeatureFlag = await this.featureFlagsRepository.findOne({
64 where: {
65 id,
66 },
67 });
68 if (updatedFeatureFlag) {
69 return updatedFeatureFlag;
70 }
71 throw new NotFoundException();
72 }
73
74 async delete(id: number) {
75 const deleteResponse = await this.featureFlagsRepository.delete(id);
76 if (!deleteResponse.affected) {
77 throw new NotFoundException();
78 }
79 }
80
81 async isEnabled(name: string) {
82 const featureFlag = await this.getByName(name);
83 if (!featureFlag) {
84 return false;
85 }
86 return featureFlag.isEnabled;
87 }
88}The above service is a good candidate for caching. If you want to know how to do it, check out API with NestJS #23. Implementing in-memory cache to increase the performance and API with NestJS #24. Cache with Redis. Running the app in a Node.js cluster
Besides creating a service, we can also define a controller that allows us to manage feature flags through the REST API.
1import {
2 Body,
3 ClassSerializerInterceptor,
4 Controller,
5 Delete,
6 Get,
7 Param,
8 Patch,
9 Post,
10 UseGuards,
11 UseInterceptors,
12} from '@nestjs/common';
13import FeatureFlagsService from './featureFlags.service';
14import JwtAuthenticationGuard from '../authentication/jwt-authentication.guard';
15import CreateFeatureFlagDto from './dto/createFeatureFlag.dto';
16import FindOneParams from '../utils/findOneParams';
17import UpdateFeatureFlagDto from './dto/updateFeatureFlag.dto';
18
19@Controller('feature-flags')
20@UseInterceptors(ClassSerializerInterceptor)
21export default class FeatureFlagsController {
22 constructor(private readonly featureFlagsService: FeatureFlagsService) {}
23
24 @Get()
25 getAll() {
26 return this.featureFlagsService.getAll();
27 }
28
29 @Post()
30 @UseGuards(JwtAuthenticationGuard)
31 async create(@Body() featureFlag: CreateFeatureFlagDto) {
32 return this.featureFlagsService.create(featureFlag);
33 }
34
35 @Patch(':id')
36 @UseGuards(JwtAuthenticationGuard)
37 async updateCategory(
38 @Param() { id }: FindOneParams,
39 @Body() category: UpdateFeatureFlagDto,
40 ) {
41 return this.featureFlagsService.update(id, category);
42 }
43
44 @Delete(':id')
45 @UseGuards(JwtAuthenticationGuard)
46 async deleteCategory(@Param() { id }: FindOneParams) {
47 return this.featureFlagsService.delete(id);
48 }
49}It might be a good idea to develop a designated frontend application that uses the above API so that it is easy to use.
Checking the feature flags
The most straightforward way to check if a feature flag is enabled is using our FeatureFlagsService directly.
1import {
2 Body,
3 Controller,
4 Post,
5 ClassSerializerInterceptor,
6 UseInterceptors,
7} from '@nestjs/common';
8import { AuthenticationService } from './authentication.service';
9import RegisterDto from './dto/register.dto';
10import { EmailConfirmationService } from '../emailConfirmation/emailConfirmation.service';
11import FeatureFlagsService from '../featureFlags/featureFlags.service';
12
13@Controller('authentication')
14@UseInterceptors(ClassSerializerInterceptor)
15export class AuthenticationController {
16 constructor(
17 private readonly authenticationService: AuthenticationService,
18 private readonly emailConfirmationService: EmailConfirmationService,
19 private readonly featureFlagsService: FeatureFlagsService,
20 ) {}
21
22 @Post('register')
23 async register(@Body() registrationData: RegisterDto) {
24 const user = await this.authenticationService.register(registrationData);
25 const isEmailConfirmationEnabled = await this.featureFlagsService.isEnabled('email-confirmation');
26 if (isEmailConfirmationEnabled) {
27 await this.emailConfirmationService.sendVerificationLink(
28 registrationData.email,
29 );
30 }
31 return user;
32 }
33
34 // ...
35}The above approach might be fine if our feature is small and straightforward. But unfortunately, it could be challenging to track where we’ve used the sendVerificationLink method. So a better approach might be to use the FeatureFlagsService in the EmailConfirmationService.
1import { Injectable } from '@nestjs/common';
2import { JwtService } from '@nestjs/jwt';
3import { ConfigService } from '@nestjs/config';
4import VerificationTokenPayload from './verificationTokenPayload.interface';
5import EmailService from '../email/email.service';
6import { UsersService } from '../users/users.service';
7import FeatureFlagsService from '../featureFlags/featureFlags.service';
8
9@Injectable()
10export class EmailConfirmationService {
11 constructor(
12 private readonly jwtService: JwtService,
13 private readonly configService: ConfigService,
14 private readonly emailService: EmailService,
15 private readonly usersService: UsersService,
16 private readonly featureFlagsService: FeatureFlagsService,
17 ) {}
18
19 private isEnabled() {
20 return this.featureFlagsService.isEnabled('email-confirmation');
21 }
22
23 public async sendVerificationLink(email: string) {
24 if (!(await this.isEnabled())) {
25 return;
26 }
27 const payload: VerificationTokenPayload = { email };
28 const token = this.jwtService.sign(payload, {
29 secret: this.configService.get('JWT_VERIFICATION_TOKEN_SECRET'),
30 expiresIn: `${this.configService.get(
31 'JWT_VERIFICATION_TOKEN_EXPIRATION_TIME',
32 )}s`,
33 });
34
35 const url = `${this.configService.get(
36 'EMAIL_CONFIRMATION_URL',
37 )}?token=${token}`;
38
39 const text = `Welcome to the application. To confirm the email address, click here: ${url}`;
40
41 return this.emailService.sendMail({
42 to: email,
43 subject: 'Email confirmation',
44 text,
45 });
46 }
47
48 // ...
49}Disabling API endpoints
Besides affecting services, we might want to disable an API endpoint defined in a controller.
1@Post('confirm')
2async confirm(@Body() confirmationData: ConfirmEmailDto, @Req() request: RequestWithUser) {
3 const isEmailConfirmationEnabled = await this.featureFlagsService.isEnabled(
4 'email-confirmation',
5 );
6 if (!isEmailConfirmationEnabled) {
7 throw new NotFoundException(`Cannot ${request.method} ${request.url}`);
8 }
9 const email = await this.emailConfirmationService.decodeConfirmationToken(
10 confirmationData.token,
11 );
12 await this.emailConfirmationService.confirmEmail(email);
13}Unfortunately, the above logic can get quite repetitive. To deal with this, we can create a guard using the mixin pattern.
1import {
2 CanActivate,
3 ExecutionContext,
4 Injectable,
5 mixin,
6 NotFoundException,
7 Type,
8} from '@nestjs/common';
9import FeatureFlagsService from './featureFlags.service';
10
11function FeatureFlagGuard(featureFlagName: string): Type<CanActivate> {
12 @Injectable()
13 class Guard implements CanActivate {
14 constructor(private readonly featureFlagsService: FeatureFlagsService) {}
15
16 async canActivate(context: ExecutionContext) {
17 const isEnabled = await this.featureFlagsService.isEnabled(
18 featureFlagName,
19 );
20 if (!isEnabled) {
21 const httpContext = context.switchToHttp();
22 const request = httpContext.getRequest();
23 throw new NotFoundException(`Cannot ${request.method} ${request.url}`);
24 }
25 return true;
26 }
27 }
28
29 return mixin(Guard);
30}
31
32export default FeatureFlagGuard;If you want to know more about mixins, check out API with NestJS #57. Composing classes with the mixin pattern
Now, the above guard is very straightforward and makes our code clean and simple.
1import {
2 Controller,
3 ClassSerializerInterceptor,
4 UseInterceptors,
5 Post,
6 Body,
7 UseGuards,
8 Req,
9} from '@nestjs/common';
10import ConfirmEmailDto from './confirmEmail.dto';
11import { EmailConfirmationService } from './emailConfirmation.service';
12import JwtAuthenticationGuard from '../authentication/jwt-authentication.guard';
13import RequestWithUser from '../authentication/requestWithUser.interface';
14import FeatureFlagGuard from '../featureFlags/featureFlag.guard';
15
16@Controller('email-confirmation')
17@UseInterceptors(ClassSerializerInterceptor)
18export class EmailConfirmationController {
19 constructor(
20 private readonly emailConfirmationService: EmailConfirmationService,
21 ) {}
22
23 @Post('confirm')
24 @UseGuards(FeatureFlagGuard('email-confirmation'))
25 async confirm(@Body() confirmationData: ConfirmEmailDto) {
26 const email = await this.emailConfirmationService.decodeConfirmationToken(
27 confirmationData.token,
28 );
29 await this.emailConfirmationService.confirmEmail(email);
30 }
31
32 @Post('resend-confirmation-link')
33 @UseGuards(JwtAuthenticationGuard)
34 @UseGuards(FeatureFlagGuard('email-confirmation'))
35 async resendConfirmationLink(@Req() request: RequestWithUser) {
36 await this.emailConfirmationService.resendConfirmationLink(request.user.id);
37 }
38}Summary
In this article, we’ve gone through the feature flags and their benefits and drawbacks. While they might help us with the process of reviewing and deploying our code, we need to be aware that they might make testing more complicated. Also, we should remove the flags we don’t need anymore.
Besides the above, we’ve also implemented a mechanism for managing feature flags using a PostgreSQL database. While doing so, we’ve used the feature flags directly through a service and a guard. There is still more to feature flags, such as A/B testing, but this is a topic for a separate article, so stay tuned!