Hide secrets in a NodeJs App 🔐
June 20, 2020
#NodeJs
When your NodeJs Application needs a database connection with a user and a password or maybe it’s using some external API which needs a secret token, you have to put these secrets somewhere in a way that no one can read them and steal your precious data.
The easiest way to solve this problem is keeping secrets stored as environment variables.
The fastest way
Put the variables inside you terminal before the node
command :
\\ inside a terminal
SECRET=Secret_token_123 node index.js
and then can you access it through the variable process.env.SECRET
inside your application.
This is not the best solution because if you’re planning to save it as npm script inside your package.json, you will end with pushing your secret to you’re repository and everyone will read it.
If you want to keep the secrets available only for our Node application we can proceed in a more elegant way:
Dotenv
Dotenv is a NPM package that loads environment variable from a .env
file.
The steps to get the job done are really simple:
- Install the package through
npm install dotenv
- In the root directory of your project crate a
.env
file and write there your variable in this waySECRET=123
- In the main process of your application ( e.g. inside index.js ) require the module and call the config method:
require('dotenv').config()
- Access you secret through the
process.env
variable
Example please !
We have a project with a structure like this:
// Our project structure
├── .env
├── index.js
├── package.json
Where .env
contains the secret and index.js
want to access it.
// .env
SECRET=DotenvIsReallyCool!
// index.js
require('dotenv').config();
console.log(process.env.SECRET); // DotenvIsReallyCool!
Really easy, isn’t it ?
Pay attention 🛑
If you are using version control system like Git, put the .env
file inside your .gitignore
otherwise you will expose your secrets and using dotenv will be useless!
Using NodeJs environment variables in production
All the various cloud service providers have ways to set environment variables, so you can check it with your own provider.
For example if you’re using Heroku to host your NodeJs application, you can set the env variables directly from your application’s dashboard from the Settings tab.
Hope you enjoy this post,
Pingu 🐧