Store Secrets in NodeJS

Mar 16, 2020

This article is also cross-posted in Medium - 2020 - Store secrets in NodeJS


When developing a web app, It is almost sure that at some point, you will have to provide an access password, a user to access a certain service, call it an API, or to connect to a database, etc. It’s a bad and highly unsafe practice write these secrets directly into your code:

// Don't do this!
config.omniauth :medium, '1eb54nsm34l5o', '1emrls578shs2m4aleo49184'

So, you should do something like this:

config.omniauth :medium, ENV['MEDIUM_KEY'], ENV['MEDIUM_SECRET']

Your code, usually, is public, and easily accessible for someone, but in this way, if someone accesses your code, they will not have access to your private keys.

We’re going to use dotenv which is a zero-dependency module that loads environment variables from a .env file into process.env.

Rails Solution

  • The first step is to add the gem ‘dotenv’ to the Gemfile:
gem 'dotenv', '~> 2.7.5'
  • Then you should install the gem using bundle:
bundle install
  • Inside your working directory you should create a .env file:
touch .env
  • Write all your secrets into this file:
MEDIUM_KEY = 1eb54nsm34l5o
MEDIUM_SECRET = 1emrls578shs2m4aleo49184
DATABASE_USER = MyUser
DATABASE_PASSWORD = MySecretPassword
  • And finally, you have to load this file when the server is initialized, so in the applicationcontrollerrenderer add this line:
require 'dotenv/load'
  • That’s it! If you restart the server you’ll have access to all variables saved in the .env file. Just don’t forget to add this file to the .gitignore, so you keep this file private.

NodeJS Solution

  • The first step is to add the module dotenv to package.json:
"devDependencies": {
  "dotenv": "^8.2.0"
}
  • Then, install the module:
yarn install
  • Inside your working directory you should create a .env file:
touch .env
  • Write all your secrets into this file:
MEDIUM_KEY = 1eb54nsm34l5o
MEDIUM_SECRET = 1emrls578shs2m4aleo49184
DATABASE_USER = MyUser
DATABASE_PASSWORD = MySecretPassword
  • And finally, you have to load this file when the server is initialized, so edit the start script:
"start": "node -r dotenv/config index"

That’s it! Again, don’t forget to add this file to the .gitignore, so you keep this file private.

You can also use this to store your endpoints and other constants, so you don’t need to look at all its usages in your code when you change it.

Feel free to check the official doc of dotenv: https://github.com/motdotla/dotenv