![]() |
VOOZH | about |
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.
If you haven't created a NestJS project, run the following command to set up a new one:
npx @nestjs/cli new nestjs-env-demoNavigate to the project directory:
cd nestjs-env-demoInstall the @nestjs/config package to manage environment variables easily in your NestJS project.
npm install @nestjs/configIn the root of your project, create a file called .env to store your environment variables:
PORT=3000
DATABASE_URL=mongodb://localhost:27017/mydb
"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"
}
To load environment variables, modify your src/app.module.ts file:
Now, run the application:
npm run startWhen you open http://localhost:3000/ in your browser, you should see:
Hello! Your database is running at: mongodb://localhost:27017/mydb