Use of Dotenv in nestjs

Dotenv is a zero - dependency module, which can convert variables in environment variables from The env file is loaded into process Env.

Installing dotenv in a project using

npm install dotenv -S

Create under the root directory env file


App. In the root directory JS and use dotenv

require('dotenv').config({ path: '.env' })

// use
console.log(process.env.HOST) // localhost
console.log(process.env.PORT) // 3000
console.log(process.env.MONGOOSE_URL) // mongodb://localhost:27017/test

How to use dotenv in nest JS?

When using environment variables in nestjs, it is recommended to use the official @ nestjs/config, which can be used out of the box:

@nestjs/config depends on dotenv. You can configure environment variables in the form of key=value. The project will load the environment variables in the root directory by default env file, we just need to in app module. TS, using ConfigModule Forroot () method, and then ConfigService reads the relevant configuration variables.

  1. First install the corresponding npm package
  2. Configure environment variable file
  3. Defines a function that reads environment variables
  4. How to configure @ nestjs/config

First install @ nestjs/config

Configure environment variable file. Configure two files, one for development environment and one for production environment EN file file

// Database address
// Database port
// Database login
// Database login password
// Database name

. env. The database information in prod is the database information to be used online. If your project needs to be uploaded to online management, it is recommended to add this file to for security reasons gitignore. Next, create a config folder (the same level as src) in the root directory, and then create an env TS is used to read the corresponding configuration files according to different environments.

This file is used to judge whether the current environment is a development environment or a test environment:

import * as fs from 'fs';
import * as path from 'path';
const isProd = process.env.NODE_ENV === 'production';

function parseEnv() {
  const localEnv = path.resolve('.env');
  const prodEnv = path.resolve('');

  if (!fs.existsSync(localEnv) && !fs.existsSync(prodEnv)) {
    throw new Error('Missing environment profile');

  const filePath = isProd && fs.existsSync(prodEnv) ? prodEnv : localEnv;
  return { path:filePath };
export default parseEnv();

The above file execution returns an object:

{path:'Environment variable file'}

Then configure the method of @ nestjs/config

import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigService, ConfigModule } from '@nestjs/config';
import envConfig from '../config/env';

  imports: [
    isGlobal: true,  // Set to global
    envFilePath: [envConfig.path] 
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        type: 'mysql', // Database type
        entities: [],  // Data table entity
        host: configService.get('DB_HOST', 'localhost'), // Host, localhost by default
        port: configService.get<number>('DB_PORT', 3306), // Port number
        username: configService.get('DB_USER', 'root'),   // user name
        password: configService.get('DB_PASSWORD', 'root'), // password
        database: configService.get('DB_DATABASE', 'blog'), //Database name
        timezone: '+08:00', //Time zone configured on server
        synchronize: true, //The database table is automatically created according to the entity. It is recommended to close the production environment
export class AppModule {}

The forRoot function parameter of ConfigModule is an object. The more important properties are isGlobal and envFilePath. This envFilePath is the environment variable configuration file read according to the environment variable.

So how to read process Where's env? Directly call the get method of configService. The first parameter of the get method is the environment variable attribute, and the second parameter is the default value.

The above is the method of using dotenv in nest JS. I hope it will help you.

Added by trooper on Mon, 20 Dec 2021 07:49:45 +0200