How do I use Build Environment Variables in Netlify with Create-React-App?
Site settings > Build & deploy > Environment > Environment variables , to be exact, ooh or Team settings > Sites > Global site settings > Shared environment variables if you're the "sharing is caring" type. These can also be set using the Netlify configuration file, netlify. toml .
To create a new Netlify application, go to your Netlify dashboard and click the New Site from Git button. Next, select GitHub as your provider and search for the project. Select the project and go to the next step to select a branch for Netlify to deploy from. Select your decoy branch.
You can access it from process. env. NODE_ENV . This variable changes based on what mode you are currently in.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With