Skip to main content

How to use env variables in a Nest JS project

The best way to handle env variables in a NestJS project is using @nest/config library. It internally uses dotenv-expand.

Best practices

Validating env variables

To validate env variables consider using joi. Its very simple and can help you to avoid env variables issues in the different environments. You can read about joi here

Steps to start working with env variables

  1. Create .env file in the root of your repository
  2. Add .env to your .gitignore
  3. yarn add @nest/config
  4. yarn add joi
  5. Import it in the app.module.ts
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import * as Joi from "joi";

@Module({
imports: [
ConfigModule.forRoot({
cache: true,
validationSchema: Joi.object({
NODE_ENV: Joi.string()
.valid("development", "test", "production")
.default("development"),
PORT: Joi.number().required(),
}),
}),
],
})
export class AppModule {}

In your .env file

PORT=3100

How to use env variables in each environment

For local environment you use the .env file.

For other environments you should set the same env variables that you set in your .env file as server variables. When the app bootstrap the config module checks if it's a .env file, if it's not it takes it from the server.