Skip to content
Advertisement

.env for prod and developpment with nodejs

I saw lot of different ways, some looked normal some others looked a bit more patchworked.

Can we use package json script to chose our env variables ? What is the right way to do it with nodeJS and how to do it ?

I have already made an .env. It contains api keys which are global for dev and prod. But I have some variables, the URL variable for exemple, which won’t be the same depending on dev or prod.

Here are my scripts in the package.json

JavaScript

Advertisement

Answer

  1. Use cross-env package to define a NODE_ENV for the command you are running. e.g. “prod”: “cross-env NODE_ENV=production node app.js”
  2. In the code, read the env file based on the NODE_ENV config. FWIW dotenv package can help with reading .env files.
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement