Setting Up Environment Variables and Configurations in NestJS
When developing a NestJS application, managing configuration and environment variables efficiently is crucial, especially when dealing with sensitive data. This guide will show you how to set up environment variables using the .env
file, and how to manage different configurations for various environments like development and production.
The env
helps in keeping sensitive data like database credentials and API keys secure and separate from your source code.
Prerequisites
Before we begin, ensure you have the following installed on your machine:
- Node.js (version >= 16)
- NPM
- MySQL server
- A basic NestJS application (refer to our article “Getting Started with NestJS” if needed)
Setup and access env file
Step 1: Create Environment Files
In the root directory of your application, create a .env
file to define your environment variables. The basic notation is a key-value pair format, as shown below:
APPNAME='NestJS-Application'
APPVERSION='v1.0'
APP_PORT=4000
HOST='localhost'
DB_PORT=3306
USERNAME='root'
PASSWORD='root'
DATABASE='nestjs'
For different environments, you can manually create multiple .env
files, such as:
.env.development
ordevelopment.env
.env.production
orproduction.env
Step 2: Install dotenv Package
To access these environment variables within your application, install the dotenv
package:
$ npm install --save dotenv
To use different environments files we have to config the .env
in main file.
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as dotenv from 'dotenv';
dotenv.config({ path: process.cwd() + '/.env.development' });
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.APP_PORT);
console.log(`This application is running on: ${await app.getUrl()}`);
}
bootstrap();
- The cmd method will return the current working directory of the Node.js process.
.env.development
is a file which i am using for storing environmental variables.- If you are using normal
.env
file. The above import and config steps are not required, you can directly use variables in application.
Step 3: Setting NODE_ENV in Different Operating Systems
This step is used to access the different env file in different environment. This NODE_ENV can be used to differentiate different application environment. we will use this value in future development of application and it is set in application run scripts which are in package.json
file:
On Unix-based systems (Linux, macOS):
You can set the NODE_ENV
variable, In start script of application. For example, to start the application in production mode.
"scripts": {
"start:dev" : "NODE_ENV=development nest start --watch",
"start:prod": "NODE_ENV=production node dist/main" // replace the existing script
}
On Windows:
On Windows, setting environment variables can be slightly different. Here are a few ways to do it:
Using set
command:
"scripts": {
"start:dev" : "set NODE_ENV=development && nest start --watch",
"start:prod": "set NODE_ENV=production && node dist/main" // replace the existing script
}
Using cross-env
package:
- The
cross-env
package allows you to set environment variables across platforms. First, install the package:
$ npm install --save-dev cross-env
2. Then, modify your package.json
scripts to use cross-env
:
"scripts": {
"start:dev" : "cross-env NODE_ENV=development nest start --watch",
"start:prod": "cross-env NODE_ENV=production node dist/main" // replace the existing script
}
Now, you can run your application with:
$ npm run start:prod
Step 4: Config and Access Environment Variables in Your Application
You can access the environment variables using process.env.<key>
. By default the the “Node.process” will search for .env
file.
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as dotenv from 'dotenv';
dotenv.config({ path: process.cwd() + '/.env.development' });
// the cmd method will return the current working directory of the Node.js process.
// .env.development is a file which i am using to storing environmental variables.
// if you are using normal .env file, the above import and config steps are not required.
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.APP_PORT);
console.log(`This application is running on: ${await app.getUrl()}`);
}
bootstrap();
Ensure your
.env
files are added to.gitignore
to prevent them from being included in version control.
Additional Best Practices
- Do Not Commit
.env
Files: Ensure your.env
files are added to.gitignore
to avoid committing sensitive information to version control.
# dotenv environment variable files
.env
development.env
.env.development.local
.env.test.local
production.env
.env.production.local
.env.local
*.env.*
2. Validate Environment Variables: Use a validation library like joi
to ensure that all required environment variables are set and valid.
Conclusion
Setting up environment variables using the dotenv
package in a NestJS application helps in managing different configurations for various environments. By creating separate .env
files for each environment and loading them appropriately, you can ensure that your application uses the correct settings in development, testing, and production.
This method not only simplifies the configuration management but also enhances the security by keeping sensitive information such as database credentials out of the source code.
Contribution
If you like my Article, please, consider donating through Buy Me a Coffee: https://buymeacoffee.com/bhargavachary.
If you think this article has been useful to you, please do not hesitate to leave your clap 👏 and leave a comment.
Thanks for reading this far!