create-react-app and .env configuration
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:
- Writing the config into some files.
- 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.

