Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

How to hide your API keys from public in ReactJS?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

An API (Application Programming Interface) key is a unique identifier used to authenticate a user, developer, or calling program to an API. However, they are typically used to authenticate a project with the API rather than a human user.

And while using the online services many times, these keys get into the wrong hands, which can be very dangerous for the original owner. Thus, keeping the API key secure is very important to prevent it from ending up in the wrong place.

One of the most common practices to secure the API key when using ReactJS is to hide the API key using env variables. Create a .env file in your root directory and make an env variable using the prefix REACT_APP. For example, as shown below:

REACT_APP_KEY = hello_world

Note: The declaration should be exact, with no space in-between.

Now, you can use the key using process.env object by importing the file to your App.js file. And before pushing the code to GitHub or Heroku, delete the .env file and use the key management system of the platform.

Steps to keep your API keys safe:

  1. Creating .env file:Just create a .env named file in the root directory of your React project as shown below:
  2. Creating env variables in .env file: Using the prefix REACT_APP, create your own env variables and assign the key as shown below:

    Filename: .env

    REACT_APP_API_KEY = Your_api_key
    // Example
    REACT_APP_API_KEY = 6341454121

    Note: Make sure to not use any space in-between as it may cause errors.

  3. Add .env file to your .gitignore file: This prevents Github from pushing the .env file to a remote repository. Avoid pushing your API keys in a public repository.
    Filename: .gitignore

    # API keys
    # Bower dependency directory (
    # node-waf configuration
  4. Accessing the API key: The API key can be accessed easily using the process.env object. Just simply import the file to your main file and access it using process.env.your_key_name.

    Filename: App.js

    import React, { Component } from 'react';
    import './App.css';
    // Accessing your defined KEYS in .env file
    // Rest of your program
    function App()
    { ... }

Now, you’re good to go and use the online servers to push your code without worrying about your keys getting public.

My Personal Notes arrow_drop_up
Last Updated : 10 Dec, 2020
Like Article
Save Article
Similar Reads
Related Tutorials