DEV Community

Cover image for How to manage environment secrets and credentials in a Nodejs application
Naftali Murgor
Naftali Murgor

Posted on • Updated on

How to manage environment secrets and credentials in a Nodejs application

Introduction

In this blog article, we will see how we can programmatically store and read environment secrets in a Nodejs application.

Ideally, we'd want to avoid:

  • hard-coding API KEYs, PRIVATE KEYs, WALLET SEED phrases, we might end up pushing this sensitive data to a VCS like GitHub or Bitbucket
  • exposing sensitive these credentials while in use.
  • make these credentials configurable

Let's jump in.
You can find all project code here: manage environment secrets

1. add a .gitignore file to root of project.

The first step would be creating a .gitignore file. This file will contain an entry of files and directories that we want git to ignore so we don't accidentally add the files to version control.

Add .env to the .gitignore file, like:

Inside file: .gitignore

.env
// other entries to be ignored by git
node_modules
Enter fullscreen mode Exit fullscreen mode

2. create a .env file

Create a file named .env at the root of your project.
Inside the file, add a key value pair of your credentials like this(no double quotes)

API_KE=your_value
MNEMOMIC=mnemonic
Enter fullscreen mode Exit fullscreen mode

3. Read environment secrets from the .env file

  • Add dotenv dependency to your project
 yarn add dotenv
Enter fullscreen mode Exit fullscreen mode

Then from where we want to read environmnent secrets:

  • Import the dotenv dependency:
const dotenv = require('dotenv')
// or with ESM
import dotenv from 'dotenv'

// read and make secrets from the .env entries available:
dotenv.config()
Enter fullscreen mode Exit fullscreen mode

Call dotenv.config() to make the secrets available from the process.env object

const MNEMONIC = process.env.MNEMEONIC
console.log(MNEMONIC) // prints 'mnemomic`
Enter fullscreen mode Exit fullscreen mode

Summary

The goal of hiding environment secrets is to hide sensitive information within our applications. Care must however be taken not to add, commit and push .env files to version control as they might end up in the wrong hands.

Here's what might happen, if one accidentally pushes PRIVATE key to Github, a bot may grab the private key, restore your wallet and drain all your ETH or BTC in a matter of seconds.

Did I miss anything? Feel free to leave a comment, a complement and honest feedback.

Do you feel stuck with learning modern JavaScript? You may preorder Modern JavaScript Primer for Beginners where I explain everything in a clear and straight-forward fashion with code examples and project examples.

Happy hacking!
This article was originally published at https://naftalimurgor.netlify.com

Top comments (0)