Detailed explanation of Nest.js environment variable configuration and serialization

Detailed explanation of Nest.js environment variable configuration and serialization

A brief description of environment variable configuration

The program requires different environment variables in different environments. For example, the production environment, test environment, and development environment require different database information: link address, link port number, login user name, and password related information. In order to solve this problem, relevant operations need to be performed.

The best approach in Nest is to create a ConfigModule that exposes a ConfigService where you load environment-specific .env files. Nest provides @nestjs/config out of the box.

Configuration

The npm ecosystem has many related dependency packages, such as the simplest:

yarn add dotenv-flow
yarn add @types/dotenv-flow -D

After installation, use it directly in main.ts:

import * as dotenv from 'dotenv-flow'

/**
 * Import .env environment * https://www.npmjs.com/package/dotenv-flow
 */
dotenv.config()

You can use the corresponding environment .env variables, but use the official recommended package: @nestjs/config:

yarn add @nestjs/config

Configure environment variables .env parsing in the forRoot static method in app.module.ts:

import { Module } from '@nestjs/common'
import { ConfigModule } from '@nestjs/config'

@Module({
 imports: [ConfigModule.forRoot()]
})
export class AppModule {}

Then create a new .env file in the project root directory:

DATABASE_USER=
DATABASE_PASSWORD=
DATABASE_NAME=
DATABASE_PORT=
DATABASE_HOST=

Custom env path

If .env needs to be refined for production, test, and development environments, it can be configured as follows:

ConfigModule.forRoot({
 envFilePath: ['.env.development.local', '.env.development'],
})

The one that is sorted earlier has the highest priority, but setting the environment variable in the startup command has the highest priority, for example:

export DATABASE_USER=root && nest start

Custom configuration files

For complex projects, you need to collect the configurable variables used, such as creating a new src/config/configuration.ts:

export default () => ({
 port: parseInt(process.env.PORT, 10) || 3000,
 database: {
  host: process.env.DATABASE_HOST || 'localhost',
  port: parseInt(process.env.DATABASE_PORT, 10) || 3306
 }
})

Then load it in ConfigModule.forRoot:

import configuration from './config/configuration'

@Module({
 imports: [
  ConfigModule.forRoot({
   load: [configuration]
  })
 ]
})
export class AppModule {}

Reading Configuration Variables

If you need to read related configuration variables, you need to use ConfigService and introduce it in the *.module.ts file used:

@Module({
 imports: [ConfigModule],
 // ...
})

If there are many places involved, it is annoying to import each module. You can do it in the app.module.ts above.

Add a field:

import configuration from './config/configuration'

@Module({
 imports: [
  ConfigModule.forRoot({
   isGlobal: true,
   load: [configuration]
  })
 ]
})
export class AppModule {}

Then inject it in the constructor:

import { ConfigService } from '@nestjs/config'

constructor(private configService: ConfigService) {}

Get configuration variables such as:

const dbUser = this.configService.get<string>('DATABASE_USER')
const dbHost = this.configService.get<string>('database.host')

Serialization

Serialization refers to the process before a program returns an object in a network response and sends it. The provided information must be converted and cleaned before it can be sent to the client: for example, when querying a user, the current user entity information can generally be returned, but the password information in it cannot be sent to the client, so some conversion must be done here.

Fortunately, Nest provides a very useful package called class-transformer:

yarn add class-transformer

For example, the following user entity information excludes password information:

import { Exclude } from 'class-transformer'

export class UserEntity {
 id: number
 firstName: string;
 lastName: string;

 @Exclude()
 password: string;

 constructor(partial: Partial<UserEntity>) {
  Object.assign(this, partial);
 }
}

Then process the query user method in the controller:

@UseInterceptors(ClassSerializerInterceptor)
@Get(':id')
findOne(@Param('id') id: string): Promise<UserEntity> {
 return this.userService.findOne(id)
}

The final query omits the password display.

Summarize

This is the end of this article about Nest.js environment variable configuration and serialization. For more related Nest.js environment variable configuration content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

<<:  The difference between Decimal type and Float Double in MySQL (detailed explanation)

>>:  How to install Nginx in CentOS7 and configure automatic startup

Recommend

TypeScript generic parameter default types and new strict compilation option

Table of contents Overview Create a type definiti...

Summary of some thoughts on binlog optimization in MYSQL

question Question 1: How to solve the performance...

The whole process of IDEA integrating docker to deploy springboot project

Table of contents 1. IDEA downloads the docker pl...

MySQL scheduled backup solution (using Linux crontab)

Preface Although some love in this world has a pr...

Introduction to major browsers and their kernels

Trident core: IE, MaxThon, TT, The World, 360, So...

React ref usage examples

Table of contents What is ref How to use ref Plac...

CSS realizes the scene analysis of semi-transparent border and multiple border

Scenario 1: To achieve a semi-transparent border:...

K3s Getting Started Guide - Detailed Tutorial on Running K3s in Docker

What is k3d? k3d is a small program for running a...

How to import js configuration file on Vue server

Table of contents background accomplish Supplemen...

Vue implements an example of pulling down and scrolling to load data

Table of contents Step 1: Installation Step 2: Ci...

vue2.x configuration from vue.config.js to project optimization

Table of contents Preface vue.config.js configura...

Detailed explanation of several ways to create objects and object methods in js

This article is the second article about objects ...