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 an .env
file to define your environment variables. Use a simple 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
Note: By default, the application checks for an .env
file. If you want to use different environment files for each environment, follow the steps below.
Step 3: Setting NODE_ENV in Different Operating Systems
Setting the NODE_ENV
variable allows you to differentiate between environments. You can configure this in the application run scripts in your package.json
file.
On Unix-based systems (Linux, macOS):
In your package.json
, modify the scripts to set NODE_ENV
:
"scripts": {
"start:dev" : "NODE_ENV=development nest start --watch",
"start:prod": "NODE_ENV=production node dist/main" // replace the existing script
}
On Windows:
There are two common methods to set environment variables on Windows:
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
Then, update your package.json
scripts:
"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
Access the environment variables using process.env.<key>
. By default, Node.js will search for an .env
file. If you are using multiple .env
files, configure dotenv
as follows:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as dotenv from 'dotenv';
dotenv.config({ path: process.cwd() + `/.env.${process.env.NODE_ENV}` });
// OR
// dotenv.config({ path: process.cwd() + `/${process.env.NODE_ENV}.env` });
/*
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();
Security Tip: Ensure your
.env
files are added to.gitignore
to prevent them from being committed to version control.
Additional Best Practices
- Do Not Commit
.env
Files: Add your.env
files to.gitignore
to avoid exposing sensitive information.
# 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 all required environment variables are set and valid.
Conclusion
Setting up environment variables using the dotenv
package in a NestJS application simplifies configuration management across various environments. By creating separate .env
files for development, testing, and production, you ensure your application uses the correct settings and keeps sensitive information such as database credentials secure.
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!