top of page
Writer's pictureTandid Alam

Methods to Storing Secrets

How to hide sensitive information within your application using secrets


The dotenv package helps hide sensitive keys and information necessary for your app to access outside sources.


Let's say you have an authorization key or password in your code and push it into your public Github repository. This can lead to potential consequences where your data can be manipulated or tampered with. That being said, it's a best practice to store sensitive keys in variables within hidden files. That's where dotenv files comes in.


To start, install dotenv in the root of your app through your terminal.

npm install dotenv --save


Next, create a .env file on the root of your app and make sure it stays hidden with a .gitignore file. This file prevents files from being committed to Github, so these files are for you to see only.


Now that you have your .env file, you can place keys and values to access later in your code. Your file can look something like this:

PORT: 3000
USER: John
Password: 1234

"You don't have to surround your key-value pairings with quotations since you will parse these later"



Now to access your variables, go to your index.js file or your main backend file and place the following code:

const dotenv = require("dotenv").config();
console.log(dotenv.parsed)


With this, you'll see the code that's in your .env file and now you can replace any piece of code with the key-value pairing using process.env followed by your KEY. For example:

process.env.PORT //Returns '3000'
process.env.USER //returns 'John'


Resources:

Comments


bottom of page