How To Configure And Use Environment Variables in NestJS?
Last Updated :
12 Sep, 2024
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
Folder StructureDependencies
"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
JavaScript
// src/app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) { }
@Get()
getHello(): string {
return this.appService.getHello();
}
}
JavaScript
//app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule { }
JavaScript
//app.service.ts
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class AppService {
constructor(private configService: ConfigService) { }
getHello(): string {
const dbUrl = this.configService.get<string>('DATABASE_URL');
return `Hello! Your database is running at: ${dbUrl}`;
}
}
JavaScript
//main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
const port = configService.get<number>('PORT') || 3000; \
await app.listen(port);
console.log(`Application is running on: http://localhost:${port}`);
}
bootstrap();
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
Similar Reads
How to Use Environment Variables in Vite? In order to create your Vite application in different environments such as development, staging and production, you need to use environment variables. They enable you to manage confidential data like API keys or service URLs without having to code them inside your source code. By using environment v
2 min read
Edit and set environment variables in Postman In Postman, the "environment" refers to a set of key-value pairs or a collection of variables used to customize requests. Environments allow you to define variables that can be reused across multiple requests, making it easier to manage different configurations for testing APIs or web services. Feat
2 min read
How To Set Environment Variables In Jenkins ? Jenkins is a widely used open-source automation server that facilitates continuous integration and continuous delivery (CI/CD) processes. One powerful feature of Jenkins is its capability to configure environment variables, which are important for various functions like defining parameters, paths, a
6 min read
How Can I Use Vite Env Variables in vite.config.js? Vite is a fast and modern front-end build tool that provides an efficient way to develop web applications. One of its powerful features is the ability to use environment variables, which can help you customize your app's behaviour based on different environments.This guide will walk you through how
4 min read
Environment Variables are Undefined in Next.js App Environment variables play a crucial role in web development, especially in configuring sensitive information such as API keys, database URLs, and other configuration settings. If your environment variables are showing up as undefined in your Next.js app, it can disrupt functionality. This issue typ
3 min read
NODE_ENV Variables and How to Use Them ? Introduction: NODE_ENV variables are environment variables that are made popularized by the express framework. The value of this type of variable can be set dynamically depending on the environment(i.e., development/production) the program is running on. The NODE_ENV works like a flag which indicate
2 min read
How to Run, Configure, and Troubleshoot npm Scripts? npm (Node Package Manager) is not only used for managing dependencies in Node.js projects but also provides a powerful script-running functionality. npm scripts allow you to automate various tasks such as running tests, building your project, deploying applications, and more. This guide will walk yo
5 min read
How to print a variable directly using EJS template engine? EJS (Embedded JavaScript) is a templating engine for NodeJS that enables dynamic content generation in web applications. To print a variable directly in an EJS template, you can use the <%= variable %> syntax. This syntax allows you to embed and display the value of a variable directly within
2 min read
How to Configure Vite for Different Environments? Vite is a modern build tool that puts the developer experience at its core, allowing you to have a fast development environment using a bare minimum of setup. It supports front-end frameworks like React, Vue, and Svelte. Configuring Vite for different environments is essential in managing API endpoi
5 min read
Environment Variables in ElectronJS ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.
7 min read