npm environment variables

You can access npm environment variables from package.json vars:

$ npm run env | grep npm_package_

But to load them in your Node.js module, you’ll need dotenv and dotenv-expand.


Make sure you have a package.json. If you don’t have one, create one:

$ npm init # --yes

Install both dotenv and dotenv-expand:

$ npm install dotenv dotenv-expand

Create a .env file with your expanded environment variables:

# .env

Load the environment variables in your module index.js:

// index.js
const dotenv = require('dotenv');
const dotenvExpand = require('dotenv-expand');


console.log(process.env.NAME, process.env.VERSION);

If you run the command:

$ node index.js

You won’t see anything logged to the console.

That’s because npm environment variables are only available via npm.

So create an npm script in your package.json:

  "scripts": {
    "start": "node index.js"

Then when you run the script:

$ npm start

You will see the package name and version logged to the console.


See example gist below:

If you enjoyed this post, please consider supporting this site!