How to set environment variables from within package.json?

Sometimes, we want to set environment variables from within package.json.

In this article, we’ll look at how to set environment variables from within package.json.

How to set environment variables from within package.json?

To set environment variables from within package.json, we can put the keys and values of the environment variables before the command we run.

For instance, we write

...
"scripts": {
  "start": "node app.js",
  "test": "NODE_ENV=test mocha --reporter spec"
},
...

to add the test script that sets the NODE_ENV environment variable to test.

And then we run the mocha command with the environment variable set.

Conclusion

To set environment variables from within package.json, we can put the keys and values of the environment variables before the command we run.