Andre Baltieri
Andre Baltieri

Reputation: 435

NestJs load environment variables on npm start

There`s a more easy way to load your env vars using .env files.

Just add --require dotenv/config to your start script, like: node --require dotenv/config server.js. https://github.com/motdotla/dotenv

But, the problem is that this does not seems to work with nodemon and I can`t figure out how to do it. I tried:

 "start:dev": "nodemon --require dotenv/config",

Can someone help?

Upvotes: 2

Views: 2256

Answers (2)

Muhammad Awais
Muhammad Awais

Reputation: 1966

if someone has reached here looking for a generic answer of how to set environment variables in nestjs then you got to read this official docs Nestjs Configuration

Upvotes: 0

Kim Kern
Kim Kern

Reputation: 60357

According to this GitHub issue, nodemon does not accept cli parameters for node. However, you can use this workaround to pass params:

nodemon --exec "node -r dotenv/config" index.js

You can put this in your npm start command by editing the package.json:

"start": "ts-node -r tsconfig-paths/register -r dotenv/config src/main.ts",
                                              ^^^^^^^^^^^^^^^

If you want to use it in the start:dev command, edit the nodemon.json file:

"exec": "ts-node -r tsconfig-paths/register -r dotenv/config src/main.ts"
                                            ^^^^^^^^^^^^^^^^

Upvotes: 4

Related Questions