Let's say you are working on a project and pulling some data from external API, for security reasons you want to hide that API key before pushing it to GitHub or any other source.
It's a way for websites to know that you are trying to access the data from their database. When you make a call, that website will use your unique key to see who you are and what kind of data you need to access.
You want to store your API key as variable in your environment. I will show you how to do it with a node package called
Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology.
Open up your terminal and type:
npm install dotenv
Make sure you successfully installed it in package.json.
To tell your server to load
dotenv you will add this line of code to your file(index.js)
You will create a new file inside of your project, called
.env and add your API key.
To make sure you did everything right, you can call
Now you can change your variable from this,
const api_key = '1233y7wt6ef5dfw8hw'
const api_key = process.env.API_KEY
Your fetch request will look like this
Before deploying your project you will need to do a few more step to secure your API Key.
.gitignorefile inside your project. A gitignore file specifies intentionally untracked files that Git should ignore.
Inside .gitignore type:
Now make sure you save all changes and you can safely deploy your project and be sure that your API key will not be floating around.