create-react-app and .env configuration

Andrei
Andrei
Sep 4, 2018 · 2 min read

Let’s say you have a React app where you’re consuming an external API. It uses one set of credentials when developing locally, and another one when deployed to production.

It’s a recommended practice to store your configuration in files that won’t make it into version control. This means you should never keep your config in .js files that might get submitted to github.

CRA ships with a little known feature that enables you to automatically specify different configurations. Accessing this feature is as simple as:

  1. Writing the config into some files.
  2. Accessing them from code.

That’s it, no need for new packages, wiring, custom scripts, etc.

Setting up your config files

CRA uses dotenv internally, and automatically loads configuration from the configuration files if it finds them in the root of your app (e.g. where your package.json is).

The three files it tries to read are:

  • .env.development (when running the app with yarn or npm start)
  • .env.production (when running from a built instance)
  • .env.test (when testing)

Formatting:

  • Files are typical configuration files, containing FIELD_NAME=value pairs, one per line.
  • All field names must be prefixed with “REACT_APP_”. (here’s why)

Accessing your config

To access the values from inside your react code, you’ll simply need to read values from the “process.env” object (e.g. process.env.REACT_APP_API_URL).

  • You don’t need to import the object “process” from anywhere, it will simply be available (magic).
  • Some IDEs complain that the variable hasn’t been imported or is undefined, you can ignore that.

Also see: Create-react-app environments.

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