0
0
NestJSframework~30 mins

Environment variables in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Environment Variables in NestJS
📖 Scenario: You are building a simple NestJS application that needs to use environment variables to configure its behavior. Environment variables help keep sensitive data like API keys or configuration settings outside your code.
🎯 Goal: Learn how to set up environment variables in a NestJS project and access them inside a service.
📋 What You'll Learn
Create a .env file with specific variables
Configure the ConfigModule to load environment variables
Inject ConfigService to read environment variables
Use environment variables inside a service method
💡 Why This Matters
🌍 Real World
Environment variables keep sensitive data and configuration outside code, making apps safer and easier to configure for different environments like development and production.
💼 Career
Knowing how to use environment variables is essential for backend developers working with NestJS or any server-side framework to manage configuration securely and flexibly.
Progress0 / 4 steps
1
Create a .env file with variables
Create a file named .env in the root folder with these exact lines:
API_KEY=12345
PORT=3000
NestJS
Need a hint?

The .env file should be plain text with key=value pairs, no quotes.

2
Configure ConfigModule to load .env
In app.module.ts, import ConfigModule from @nestjs/config and add ConfigModule.forRoot() to the imports array inside @Module.
NestJS
Need a hint?

ConfigModule.forRoot() loads environment variables automatically.

3
Inject ConfigService in a service
Create a service named AppService with a constructor that injects ConfigService from @nestjs/config. Store it in a private readonly variable called configService.
NestJS
Need a hint?

Use dependency injection to get ConfigService instance.

4
Use environment variables inside a method
Add a method getApiKey() inside AppService that returns the value of the environment variable API_KEY using this.configService.get('API_KEY').
NestJS
Need a hint?

Use ConfigService's get method to read environment variables.