VOOZH about

URL: https://www.geeksforgeeks.org/javascript/how-to-configure-and-use-environment-variables-in-nestjs/

⇱ How To Configure And Use Environment Variables in NestJS? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How To Configure And Use Environment Variables in NestJS?

Last Updated : 5 Aug, 2025

Environment variables are an important part of application development, allowing developers to configure applications in different environments (development, staging, production) without hardcoding sensitive or environment-specific information into the application code.

In this article, we'll walk through how to configure and use environment variables in a NestJS application.

Prerequisites:

Steps to Configure and Use Environment Variables in NestJS:

Step 1: Create a New NestJS Project

If you haven't created a NestJS project, run the following command to set up a new one:

npx @nestjs/cli new nestjs-env-demo

Navigate to the project directory:

cd nestjs-env-demo

Step 2: Install @nestjs/config Package

Install the @nestjs/config package to manage environment variables easily in your NestJS project.

npm install @nestjs/config

Step 3: Create a .env File

In the root of your project, create a file called .env to store your environment variables:

PORT=3000
DATABASE_URL=mongodb://localhost:27017/mydb

Folder Structure

👁 Image
Folder Structure

Dependencies

"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/config": "^3.2.3",
"@nestjs/core": "^10.0.0",
"@nestjs/platform-express": "^10.0.0",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1"
}

Step 4: Modify AppModule to Use ConfigModule

To load environment variables, modify your src/app.module.ts file:

Example

Step 5: Run the Application

Now, run the application:

npm run start

Step 6: Check the Output

When you open http://localhost:3000/ in your browser, you should see:

Hello! Your database is running at: mongodb://localhost:27017/mydb

Output

Comment
Article Tags: