> For the complete documentation index, see [llms.txt](https://kinesis-school-of-programming.gitbook.io/nestjs-unleashed/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kinesis-school-of-programming.gitbook.io/nestjs-unleashed/core-module-backend-development-with-nestjs/configuration/availability-and-validation.md).

# 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](https://www.npmjs.com/package/dotenv) solves the first problem. Another package, [dotenv-expand](https://www.npmjs.com/package/dotenv-expand), solves the second one. Nest has a module called <mark style="color:blue;">`ConfigModule`</mark> 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](https://www.npmjs.com/package/joi).

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

```sh
yarn add @nestjs/config joi
```

Now, for better organizarion, let's create the <mark style="color:blue;">`EnvModule`</mark> to house the <mark style="color:blue;">`ConfigModule`</mark>.

```sh
nest g mo env
```

In its <mark style="color:blue;">`imports`</mark> array, add the <mark style="color:blue;">`ConfigModule`</mark> to make the environment variables accessible in the codebase.

```typescript
ConfigModule.forRoot()
```

To be able to use the URL as an **expanded variable**, activate the option <mark style="color:blue;">`expandVariables`</mark>.

And now, to validate these variables and make sure they exist and are in the correct shape, first create the file <mark style="color:purple;">env</mark>/<mark style="color:purple;">util</mark>/<mark style="color:purple;">env.constants</mark> and, in it, put the validation schema.

```typescript
export const ENV_VALIDATION_SCHEMA = Joi.object({
  DATABASE_USER: Joi.required(),
  DATABASE_PASSWORD: Joi.required(),
  DATABASE_HOST: Joi.required(),
  DATABASE_PORT: Joi.number().port().required(),
  DATABASE_NAME: Joi.required(),
  DATABASE_URL: Joi.required(),
});
```

{% hint style="info" %}
When importing **Joi**, use <mark style="color:blue;">`import * as Joi`</mark>
{% endhint %}

Back in the <mark style="color:blue;">`EnvModule`</mark>, set the option <mark style="color:blue;">`validationSchema`</mark> to the constant we just created.

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