DEV Community

Tadea Simunovic
Tadea Simunovic

Posted on

Hide and secure API key

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.

What is an API key and why you need it?

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.

How to hide?

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

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)

require('dotenv').config()

You will create a new file inside of your project, called .env and add your API key.

API_KEY=1233y7wt6ef5dfw8hw
Enter fullscreen mode Exit fullscreen mode

To make sure you did everything right, you can call
console.log(process.env)

Now you can change your variable from this,

const api_key = '1233y7wt6ef5dfw8hw'
Enter fullscreen mode Exit fullscreen mode

to this:

const api_key = process.env.API_KEY
Enter fullscreen mode Exit fullscreen mode

Your fetch request will look like this api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${Api_Key}

Before deploying your project you will need to do a few more step to secure your API Key.

Create a .gitignorefile inside your project. A gitignore file specifies intentionally untracked files that Git should ignore.
Inside .gitignore type:

.env
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)