How do I use Build Environment Variables in Netlify with Create-React-App?
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.
REACT_APP_
will be availableIMPORTANT 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/:
Netlify.com
In app.netlify.com
, CUSTOM_ENV_VAR
and REACT_APP_CUSTOM_ENV_VAR
were set as follows:
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_)"
.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.