Configure a NestJS API with Environment Variables using ConfigModule and joi

Bram Borggreve
InstructorBram Borggreve
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 4 years ago

In this lesson, we add configuration to the NestJS API using a .env file, which Nx Workspace supports out of the box.

After adding the @nestjs/config and joi dependencies, we define a configuration and validation schema.

These files are loaded into the ConfigModule, that we import in CoreModule and the values in our .env file are now validated using our schema.

We can now import the ConfigService and use it to get properties from our configuration.

Bram Borggreve: [0:00] When we create a .env file in the root of our project, we can define our environment variables. When we restart the API, we can see that the values get applied. .env files can contain secrets like database passwords, and access tokens, so it's a good idea not to add them to Git. Instead, we're going to add an entry to .gitignore so it doesn't get committed.

[0:22] Another best practice is to create a copy of the .env file and call it .env.example. That way, the next developer downloading this project knows what the shape of the .env file is like. We add the dependencies @nestjs/config and joi.

[0:38] Inside our core library, libs/core/src/lib, we create a file configuration.ts in the config folder. We make it export a constant called configuration, which is a method that returns an object. We add a key environment and assign it to the value of process.env.NODE_ENV.

[0:59] Additionally, we add a property called port and assign it to process.env.PORT. Next, we create a file called validation.ts inside the config folder. We make it export a constant called validationSchema and assign it to Joi.object.

[1:16] We add a new object which is our actual validationSchema. The first entry you want to validate is NODE_ENV. We're going to say it's a string. It has the valid options "development", "production", and "test", and it is required.

[1:29] For our PORT, we tell it that it's a number and the default value is 3000. Let's open the core.module and add an array called imports to the decorator. We import { ConfigModule } from '@nestjs/config' and call the forRoot() method on it. We set the isGlobal property to true. We load in the configuration, and the validationSchema. When we restart the server, we see that the ConfigHostModule gets loaded.

[1:54] Let's open main.ts from apps/api/src. Right below where we initialize AppModule, we create a new const called config, and assign it to app.get and add a ConfigService.

[2:05] Let's duplicate this line and make it output 'Running in ${config.get('environment')} mode'). When we now restart the API, we can see that it prints the modes in which we're in.