Using Environment Variables in React.js to Keep Your Keys Safe.

Philip Krause

Avoid exposing your private keys, passwords or other sensitive details to GitHub by storing them as environment variables.

As a recent graduate from the SunCoast Developer’s Guild,(a 12-week full-time coding boot camp), I was eager to continue learning. I’ve been trying to post to github frequently, ask questions in slack communities, and share code.

One of those sharing experiences was responded with, “I hope that’s not a real API key in the code, because now it’s out in public.”

I initially felt embarrassed, but quickly turned grateful for someone pointing it out early in my dev career. It was a free lesson, unlike this unfortunate soul.

Now there are a lot of ways to handle your keys. This tutorial will focus on using an npm package called “dotenv.”

The first step is to install the package.

npm install dotenv 

Lets now create a file in our project’s root directory called .env

This is the file where you will be storing your secret keys.

Now because we are in React, we have to preface ALL of our environment variables with “REACT_APP_”.

(using capital letters for your env vars is common practice)

REACT_APP_CLIENT_ID = secretKeyGoesHere

As early as possible in your application, we need to require, and configure dotenv. If using create-react-app, this can live in your App.js file.

require('dotenv').config({ path: '../.env' })

The path might change depending on your file structure.

We have defined our variables, and we have configured our path, let’s see them in action.

Open the file where you will be using your secret keys. To use the variables you created, preface them with


Here’s a full example

componentDidMount = async () => {await _GPS.configure({clientId: process.env.REACT_APP_CLIENT_ID,clientSecret: process.env.REACT_APP_CLIENT_SECRET,})

We do not have to import anything to this file, dotenv handles that for us.

That’s it for the dotenv, BUT there is one more step if we don’t want our .env file and secret keys ever reaching github.

If you haven’t already, add a .gitignore file to your project. Open the file and add



Now you can share your code with whomever you please without having to ever worry about your keys being exposed.

Thanks for reading. I hope you now understand the importance of using environment variables.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade