Ad

Sunday, November 14, 2021

dotenv : Setting up environment variables for dev environment

 It's very important to protect API keys, private keys in blockchain and API development. In general the best practice is: do not have API keys, or any secrets, sitting unprotected in code bases, even if it is in the server side logic. Front end code is definitely a big no no. We use environment variables to manage private keys and secrets. Some cloud platforms such as Google Cloud offers encrypted, cloud managed keys, with extra features such as key rotations, that's pretty cool.  Here're are some tips from Chainlink smart contract hardhat starter kit. 

There are two options of setting environment variables: store credentials in a .env file AND set it in command line. Remember to add any env file to .gitignore else you risk losing your credentials and subject your app to attack and misuse. Bad parties can steal your API keys make unauthorized transactions /requests and incur cost / lost.


The bash one works directly in the command line. The .env one is to be used with the dotenv npm package.

dotenv (node, npm package, weekly download 15,514,927 as of Jan 2022). "Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env." https://www.npmjs.com/package/dotenv

# with npm

npm install dotenv


# or with Yarn

yarn add dotenv

To verify installation is successful, also check the package.json file. 

require('dotenv').config()


Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE. For example:

DB_HOST=localhost

DB_USER=root

DB_PASS=s1mpl3


process.env now has the keys and values you defined in your .env file.

const db = require('db')

db.connect({

  host: process.env.DB_HOST,

  username: process.env.DB_USER,

  password: process.env.DB_PASS

})


Once we define environment variables in the .env file the values are available with the process.env. prefix. That's pretty cool. Definitely exclude the .env file form git history and git push.

The environment variables sit near the operating system, or the virtual environment the code is running on. The code only pulls the value of the secrets. "Platforms can have its own unique mechanism for storing and retrieving environment variables. " https://youtu.be/17UVejOw3zA



No comments:

Post a Comment

React UI, UI UX, Reactstrap React Bootstrap

React UI MATERIAL  Install yarn add @material-ui/icons Reactstrap FORMS. Controlled Forms. Uncontrolled Forms.  Columns, grid