How to handle secrets in Node.js πŸ—οΈπŸ—οΈπŸ—οΈ (environment variables)

Benjamin Mock - Nov 21 '19 - - Dev Community

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 to the package.json. Let's have an index.js, that looks like

const apiKey = process.env.API_KEY
console.log(apiKey)
Enter fullscreen mode Exit fullscreen mode

You can, for example, start your application with

API_KEY=super-secret-key node index.js
Enter fullscreen mode Exit fullscreen mode

You can also put the same into your package.json

  ...
  "scripts": {
    "start": "API_KEY=super-secret-key node index.js"
  },
  ...
Enter fullscreen mode Exit fullscreen mode

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.

run

npm install dotenv
Enter fullscreen mode Exit fullscreen mode

to install the library.

Then import and use it like this in your application:

require('dotenv').config();

const apiKey = process.env.API_KEY
console.log(apiKey)
Enter fullscreen mode Exit fullscreen mode

Your '.env` file will now contain your secret.


API_KEY=super-secret-key

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

Put this in the .gitignore:


.env

This way you have all your secrets in one place and you don't accidentally leak any secrets.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player