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.
.env to the
.gitignore file, like:
Inside file: .gitignore
.env // other entries to be ignored by git node_modules
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)
3. Read environment secrets from the .env file
dotenvdependency to your project
yarn add dotenv
Then from where we want to read environmnent secrets:
- Import the
const dotenv = require('dotenv') // or with ESM import dotenv from 'dotenv' // read and make secrets from the .env entries available: dotenv.config()
dotenv.config() to make the secrets available from the
const MNEMONIC = process.env.MNEMEONIC console.log(MNEMONIC) // prints 'mnemomic`
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.
This article was originally published at https://naftalimurgor.netlify.com
Top comments (0)