Creating Config Files in NestJS
Getting values from an environment file isn’t supposed to be as simple as creating a .env
file. In NodeJS, dotenv, is one of the most famous packages that adds values into the node’s process.env
and returns them as a string
. But sometimes, you need these values to as boolean (eg. for enabling/disabling a feature) or an array (eg. array of support emails)… and because now we have more than one types to play around with, validation of these incoming environment variables becomes a must.
NestJS is one of the few Node frameworks that makes creating config variables very easy. It provides with a very object-oriented, modular and structured way to deal with this.
Without any further ado, I am going to go ahead and brief you on how you can achieve the right setup for this in NestJS.
Packages Required
- @nestjs/config — This package was release a month ago (Dec 2019) by @Kamil Mysliwiec, the founder of NestJS and has official NestJS support.
- @hapi/joi — Used for creating a validation schema for incoming environment variables.
Installation
Type declarations for only @hapi/joi are required in this instance. The ones for @nestjs/config come as part of the package.
npm i @nestjs/config @hapi/joi
npm i -D…