DEV Community

Cover image for How to mask your API key?
Sarah Hassan
Sarah Hassan

Posted on

How to mask your API key?

Your API key should remain private and to achieve that Git should not track the API key. So today I will talk about two ways for masking API key, suppose you are developing a new app using React.js and have an API key to fetch news.

First one, using the environment variable

1- Create a file called .env in the project directory and define a variable with uppercase.

REACT_APP_NEWS_KEY = 'your_API_key'

2- Ignore .env file by adding its name to .gitignore file. The purpose of .gitignore file is to ensure that certain files not tracked by Git.

# api keys
.env

3- Access API key in your project using process.env.

const API_KEY = process.env.REACT_APP_NEWS_KEY;

const getPosts = async () => {
    try {
      dispatch({ type: 'SEND_REQUEST' });
      const response = await fetch(
        `https://newsapi.org/v2/everything?q=javascript&apiKey=${API_KEY}`
      );
      const data = await response.json();
      dispatch({ type: 'REQUEST_FINISH' });
      dispatch({ type: 'SET_POSTS', payload: data });
    } catch (err) {
      console.log(err);
    }
  };

Important Note: After creating the environment variable you have to restart your server to avoid getting your API key is invalid, you will receive a 401 - Unauthorized HTTP error.

Second one, using named export

1- Create a folder in src folder called config and inside it create a js file called config.js

const reactNewKey = 'your_API_key';

export { reactNewKey };

2- Ignore config.js file by adding its path in .gitignore file

src/config/config.js

3- Acess API key in your project by importing it

import { reactNewKey } from 'path_of_your_file'

Thanks for reading! I hope this article helps, feel free to share it with your friends, any feedback will be appreciated :)

Top comments (0)