DEV Community

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

Posted on

10 3

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 :)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post →

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay