Can I use Build Environment Variables in Netlify with Create-React-App?

Laura J picture Laura J · Sep 27, 2018 · Viewed 8k times · Source

How do I use Build Environment Variables in Netlify with Create-React-App?

Answer

talves picture talves · Sep 28, 2018

You CAN use environment variables in your create-react-app on Netlify, but all the build constraints of the Create React App will still apply.

  • By default you will have NODE_ENV defined for you
  • Any other environment variables starting with REACT_APP_ will be available
  • Any other variables except NODE_ENV will be ignored
  • Changing any environment variables will require you to trigger a new build/deploy

IMPORTANT NOTE: No environment variables can be accessed from a create-react-app dynamically from the browser hosted on Netlify! They must be accessed at build time to be used in the static site.


From an example create-react-app repo hosted on Netlify:

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Environment Variables in a Create React App on Netlify</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and commit to your repo.
        </p>
        <p>NODE_ENV value is "{process.env.NODE_ENV}"</p>
        <p>CUSTOM_ENV_VAR value is "{process.env.CUSTOM_ENV_VAR}"</p>
        <p>REACT_APP_CUSTOM_ENV_VAR value is "{process.env.REACT_APP_CUSTOM_ENV_VAR}"</p>
        <p>TOML_ENV_VAR value is "{process.env.TOML_ENV_VAR}"</p>
        <p>REACT_APP_TOML_ENV_VAR value is "{process.env.REACT_APP_TOML_ENV_VAR}"</p>
      </div>
    );
  }
}

export default App;

Produces the following at https://netlify-cra-env-vars.netlify.com/: enter image description here

Setting Environment Variables in site settings on Netlify.com

In app.netlify.com, CUSTOM_ENV_VAR and REACT_APP_CUSTOM_ENV_VAR were set as follows: enter image description here

Setting Environment Variables in netlify.toml

The netlify.toml environment variables were set as:

[build]
  command = "yarn build"
  publish = "build"

[context.production.environment]
  TOML_ENV_VAR = "From netlify.toml"
  REACT_APP_TOML_ENV_VAR = "From netlify.toml (REACT_APP_)"

[Extra] Setting environment variables in .env

You could set environment variables in a .env file at the root of your project and commit to your repository. The following is available with [email protected] and higher which takes your version value of your package.json file.

.env

REACT_APP_VERSION=$npm_package_version

Note: the version (and many other npm exposed environment variables) can be accessed.
Do not put secret keys into your repository.