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
... "scripts": { "dev": "nodemon app.js", "prod": "node app.js" }
Advertisement
Answer
- 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” - In the code, read the env file based on the
NODE_ENV
config. FWIWdotenv
package can help with reading.env
files.