Reading Secrets from the Environment — React & Netlify

Visakh Vijayan
2 min readFeb 29, 2024

--

The best part about being a programmer is that you are free to create projects and publish them to the world. I have been working on this silly web application that gives you a random quote for the day.

You can check the project out here — https://effervescent-sprinkles-74c791.netlify.app/

Acknowledgments

It is hosted on Netlify and has a third-party dependency from API Ninja. They are the ones who do the heavy lifting of generating the quotes. I simply display them.

Problems

But anyway, the API Key was left exposed in the code for a long time. Oops! And today I finally decided to mask them. It is a good practice to mask the secrets since public repositories are accessible to everyone and these API keys could be used for all the wrong reasons.

The process is really simple. All you have to do is —

  1. Create a .env file at the root of the project which means at the same level as your src folder.
  2. Add your secrets to it like so —

Make sure to add the prefix REACT_APP_ . This is done for security purposes by React. If not, the values don’t appear under process.env

3. Add the .env to your .gitignore file too. We don’t want this file to be committed to the repository henceforth.

4. In your code you can access them like this —

const NINJA_API_KEY = process.env.REACT_APP_NINJA_API_KEY as string;
const NINJA_URL = process.env.REACT_APP_NINJA_URL as string;

5. Go to Netlify and Visit the Site Configurationsettings. Add the variables or just import your .env file.

With that, you are good to go. You will be able to see the environment variables being read during the Build process and once deployed your site should be working as expected. Yippee!

Contribute

Don’t hesitate to contribute to the repository. I have a list of issues open that I work on regularly. You can find the open issues here — https://github.com/visakhvjn/random-quotes/issues

--

--

Visakh Vijayan
Visakh Vijayan

Written by Visakh Vijayan

Techie from Kerala, India. Days are for coding, nights for weaving tales of tech, travel, and finance. Join me in exploring this multifaceted journey

No responses yet