How to Use Environment Variables with Create-React-App

Oct 28, 2019

Environment Variables are a critical tool in getting your app set up correctly, but can be tricky for beginners. Create React App also has a couple other nuances to be aware of.

For background, environment variables are how we wire things up to behave differently between different environments (i.e. development vs production). For instance, you often need your dev environment to point to a different API, or for your payments library to only charge money in production, etc.

Setting Values

If you’re using Create-React-App, you can add your own custom environment variables.

  1. create a file called
    in the root directory of your project
  2. add a new line in the file for each variable you need, making sure to prefix the variable name with
    . For instance:

🚨 Don’t miss this! The variable name must start with

otherwise it won’t work.

  1. Restart the dev server.

Reading Values

Environment variable values can be read using

, like so:

render() {
  return (
      Current API url: {process.env.REACT_APP_API_URL}.

A few more things…

  • Client side

    values are not secret. They can be found by anyone who wants to sift through your site’s JavaScript code.

  • .env
    files should be committed and tracked in version control with the rest of your project.

  • You may want some environment variables that are only for you specifically (not necessarily others on your team) that you don’t want to be tracked via version control. For these, you can create another file in the project root, called

    . Variables placed here will override the
    value if both are present. This file should not be committed or tracked in version control.

  • Changes to

    files don’t take effect until you restart the server.

  • To comment out a line in a

    file, prefix it with a “#” character, like so:

  • Create-React-App comes with one default environment variable out-of-the-box:
    . This will be set to “development”, “test”, or “production” depending on your current environment. It can be read from

For more details, check the official Create React App docs.

Follow me on Twitter!

Want more? Did I get something wrong? @markadamfoster

Want more like this? Sign up to get one article delivered weekly by email.
© 2023 Mark Foster