CodeSnacks

Environment Variables with Node.js

July 31, 2019

What’s the best way to handle configurations or secrets like API keys with Node.js? One simple way is to use environment variables.

You could pass them directly to your node command or add them in the package.json. dotenv is probably the best way to consume these environment variables in Node.js.

run

npm install dotenv

to install the library.

The import and use it like this in your application:

require('dotenv').config();

console.log(process.env.API_KEY)

now start this with

API_KEY=bla node index.js

You can also put the same into your package.json

  ...
  "scripts": {
    "start": "API_KEY=bla node index.js"
  },
  ...

and start your application with npm start. That way you at least don’t have to type your API key every time you start your application.

The problem with this approach is, that you have to commit your package.json to your repository. But you should not share secret keys like this. So there’s a better way to do it: using a .env file.

So you can add your API key to this .env file and consume it, like before, with the dotenv library.

API_KEY=bla

Ideally you would then also create an entry in your .gitignore to exclude your .env file from versin control.

Put this in the .gitignore

.env

This way you don’t leak any secrets.