Tushar

Tushar

How not to expose your sensitive keys to Github.

A quick start guide on Environment Variables in Javascript.

Introduction -

Securing the critical data for your application is as important as implementing new features and improving UI/UX. Critical data can be anything from API keys, payment gateways to Database credentials.

As you are reading this article, you probably already know the importance of it but here are a few problems that might occur if you push API keys and other important stuff -

  • Anyone can access your cloud database/third party integrations, perform CRUD operations on your behalf which you definitely don't want to happen.
  • Some platforms like Auth0 are very strict and they might ban your account if you open-source the API keys.
  • Most Importantly - you will get the prestigious lifetime tag to leak your team's critical data.

Let's Dive deep- 🕵️‍♂️

We can do this in just 2 simple steps:

  1. Setting up .gitignore
  2. Creating Environment Variables


gitignore -

It's kinda self-explanatory, Git just ignores the files whose relative paths are stored in .gitignore.

Just create a file in the root folder named exactly .gitignore

If you're working on React or any other Framework you might already see a .gitignore file in the root directory.

  • What we need to do is just add relative paths to the file/folder we want to hide and those files will be ignored while git push.

  • Here that file is .env (we will study this later)
    Just add .env in .gitignore like this:

    // .gitignore
    .env
    


Creating Environment Variables -

Creating Environment variables is the most secure and simplest way to hide the data and still keep our project running absolutely fine.

In Javascript, we can create environment variables using: dotenv package.

Firstly install dotenv using:

npm i dotenv

Then we need to import dotenv in the file where we need the hashed keys. let's say it's app.js:

// app.js
require('dotenv').config();

Now, we have our setup ready and we can create and use our Environment Variables.

  1. Create a file in the root folder named .env. This is the place where we store our API keys and top-secret data.
  2. Declare the variables using this syntax: KEY = value.

    Note:

    1. It is best practice to keep the key Uppercase but is not a Compulsion.
    2. When working in React keys must start with "REACT_APP_"
    DB_URL = https://example.com
    USER_NAME = tushartiwari7
    USER_PASSWORD = g7538gyv
    and so on...
    
  3. Now, in app.js, we can access the variables usingprocess.env.VARIABLE_NAME such as:
require('dotenv').config();

fetch(`${process.env.DB_URL}/api/routes`)
  .then(response => response.json())
  .then(data => console.log(data));

Resources -


Conclusion -

Now we know how to hide sensitive data from open source platforms. I hope you can use them with better understanding in your projects now.

 
Share this