Create-React-App & Dotenv

Danny Kay
2 min readMay 8, 2017

--

Me and the create-react-app are the best of buddies. I can have a React app up and running in less than a minute which is great for when I’m prototyping.

If I’m building a React app, chances are I’m building an Express app for the back-end to handle the API calls through to MongoDB or PostgreSQL, and both the front and back end are stored in GitHub.

When I was first learning React I was always worried about pushing code up to GitHub which contained database or API information such as keys and URL’s, then I discovered a nifty little NPM package called dotenv.

dotenv is a module that loads variables from a .env file into process.env and is ideal for storing usernames, passwords, URL’s and other sensitive bits and bobs.

Install & Setup

It can be installed by running the command below.

npm install dotenv --S

The install instructions on the NPM site mention to require and configure as earlier as possible, id suggest either in the Index.js or App.js.

require('dotenv').config()

From there we need to create a .env file in the root directory of our project. Then we can add environment specific variables on new lines in the form of REACT_APP_SECRET=VALUE. I’ve placed a example below.

REACT_APP_DEV_API_URL="https://devapiurl.com/api/"

There is a quirk here, if we weren't using create-react-app we wouldn't have to place REACT_APP_ in front of the variable.

And that is literally it! We can now access the keys and values defined in our .env file.

SuperAgent.get(process.env.REACT_APP_DEV_API_URL)

Remember to add the .env file to your .gitignore so it doesn't find itself in GitHub.

That’s all for now, but you can check the NPM page for dotenv at https://www.npmjs.com/package/dotenv for information.

Cheers,

Dan

--

--