Availability and validation

The environment variables need to be made available and validated before use.

Before using environment variables, the following problems need to be addressed

  • They need to become available in the codebase

  • The URL is created from the other variables. In this context, this is called variable expansion and is not natively supported

  • There should be a validation of the variables before the system goes up

The package dotenv solves the first problem. Another package, dotenv-expand, solves the second one. Nest has a module called ConfigModule that uses these two packages under the hood, allowing us to solve both problems elegantly. It also allows for using a validation schema to solve the third problem, which we'll use in combination with the library joi.

That said, let's begin by installing the required dependencies.

yarn add @nestjs/config joi

Now, for better organizarion, let's create the EnvModule to house the ConfigModule.

nest g mo env

In its imports array, add the ConfigModule to make the environment variables accessible in the codebase.

ConfigModule.forRoot()

To be able to use the URL as an expanded variable, activate the option expandedVariables.

And now, to validate these variables and make sure they exist and are in the correct shape, first create, inside the env folder in util, the file env.constants and in it put the validation schema.

export const ENV_VALIDATION_SCHEMA = Joi.object({
  DATASOURCE_USERNAME: Joi.required(),
  DATASOURCE_PASSWORD: Joi.required(),
  DATASOURCE_HOST: Joi.required(),
  DATASOURCE_PORT: Joi.number().required(),
  DATASOURCE_DATABASE: Joi.required(),
  DATASOURCE_URL: Joi.required(),
});

When importing Joi, use import * as Joi

Back in the EnvModule, set the option validationSchema to the constant we just created.

Great! All the three problems have been solved. We can now proceed to actually use these variables.

Last updated