README.md
Deploy React.js web apps generated with create-react-app. Automates deployment with the built-in bundler and serves it up via Nginx. See the introductory blog post and entry in Heroku elements.
This buildpack deploys a React UI as a static web site. The Nginx web server provides optimum performance and security for the runtime. See Architecture for details.
If your goal is to combine React UI + API (Node, Ruby, Pythonβ¦) into a single app, then this buildpack is not the answer. The simplest combined solution is all javascript:
βΆοΈ create-react-app + Node.js server on Heroku
Combination with other languages is possible too, like create-react-app + Rails 5 server.
Ensure requirements are met, then execute the following in a terminal.
βοΈ Replace $APP_NAME with the name for your unique app.
npx create-react-app@2.x $APP_NAME
cd $APP_NAME
git init
heroku create $APP_NAME --buildpack mars/create-react-app
git add .
git commit -m "Start with create-react-app"
git push heroku master
heroku openOnce deployed, continue development π±
For explanation about these steps, continue reading the next section.
βοΈ Replace $APP_NAME with the name for your unique app.
npx create-react-app@2.x $APP_NAME
cd $APP_NAMEgit initAt this point, this new repo is local, only on your computer. Eventually, you may want to push to Github.
βοΈ Replace $APP_NAME with the name for your unique app.
heroku create $APP_NAME --buildpack mars/create-react-appThis command:
https://$APP_NAME.herokuapp.com
heroku git remote in the local repo, so git push heroku master will push to this new Heroku app.git add .
git commit -m "Start with create-react-app"
git push heroku masterβ¦or if you are ever working on a branch other than master:
βοΈ Replace $BRANCH_NAME with the name for the current branch.
git push heroku $BRANCH_NAME:masterheroku openFind the app on your dashboard.
Work with your app locally using npm start. See: create-react-app docs
Then, commit & deploy β»οΈ
Eventually, to share, collaborate, or simply back-up your code, create an empty repo at Github, and then follow the instructions shown on the repo to push an existing repository from the command line.
Use create-react-app's built-in Jest testing or whatever testing library you prefer.
Heroku CI is supported with minimal configuration. The CI integration is compatible with npm & yarn (see bin/test).
Heroku CI uses app.json to provision test apps. To support Heroku CI, commit this minimal example app.json:
{
"buildpacks": [
{
"url": "mars/create-react-app"
}
]
}Heroku apps may declare what processes are launched for a successful deployment by way of the Procfile. This buildpack's default process comes from heroku/static buildpack. (See: π Architecture). The implicit Procfile to start the static web server is:
web: bin/boot
To customize an app's processes, commit a Procfile and deploy. Include web: bin/boot to launch the default web process, or you may replace the default web process. Additional process types may be added to run any number of dynos with whatever arbitrary commands you want, and scale each independently.
π¦ If replacing the default web process, please check this buildpack's Purpose to avoid misusing this buildpack (such as running a Node server) which can lead to confusing deployment issues.
The web server may be configured via the static buildpack.
The config file static.json should be committed at the root of the repo. It will not be recognized, if this file in a sub-directory
The default static.json, if it does not exist in the repo, is:
{
"root": "build/",
"routes": {
"/**": "index.html"
}
}If a different web server "root" is specified, such as with a highly customized, ejected create-react-app project, then the new bundle location may need to be set to enable runtime environment variables.
π₯ Client-side routing is supported by default. Any server request that would result in 404 Not Found returns the React app.
π See custom routing w/ the static buildpack.
Enforce secure connections by automatically redirecting insecure requests to https://, in static.json:
{
"root": "build/",
"routes": {
"/**": "index.html"
},
"https_only": true
}Prevent downgrade attacks with HTTP strict transport security. Add HSTS "headers" to static.json.
β οΈ Do not set HSTS headers if the app's hostname will not permantly support HTTPS/SSL/TLS. Once HSTS is set, switching back to plain HTTP will cause security errors in browsers that received the headers, until the max-age is reached. Heroku's built-in herokuapp.com hostnames are safe to use with HSTS.
{
"root": "build/",
"routes": {
"/**": "index.html"
},
"https_only": true,
"headers": {
"/**": {
"Strict-Transport-Security": "max-age=31557600"
}
}
}max-age is the number of seconds to enforce HTTPS since the last connection; the example is one-yearProxy XHR requests from the React UI in the browser to API backends. Use to prevent same-origin errors when CORS is not supported on the backend.
To make calls through the proxy, use relative URL's in the React app which will be proxied to the configured target URL. For the example URL prefix of /api/, here's how the proxy would rewrite the requests:
/api/search-items
β https://backend.example.com/search-items
/api/users/me
β https://backend.example.com/users/me
You may choose any prefix and may have multiple proxies with different prefixes.
The heroku/static buildpack (see: π Architecture) provides Proxy Backends configuration to utilize Nginx for high-performance proxies in production.
Add "proxies" to static.json:
{
"root": "build/",
"routes": {
"/**": "index.html"
},
"proxies": {
"/api/": {
"origin": "${API_URL}"
}
}
}Then, point the React UI app to a specific backend API:
heroku config:set API_URL="https://backend.example.com"create-react-app itself provides a built-in proxy for development. This may be configured to match the behavior of proxy for deployment.
Add "proxy" to package.json:
{
"proxy": {
"/api": {
"target": "http://localhost:8000",
"pathRewrite": {
"^/api": "/"
}
}
}
}Replace http://localhost:8000 with the URL to your local or remote backend service.
REACT_APP_* environment variables are fully supported with this buildpack.
π«π€ Not for secrets. These values may be accessed by anyone who can see the React app.
heroku config:set REACT_APP_HELLO='I love sushi!'Requires at least create-react-app 0.7. Earlier versions only support Compile-time.
Create a .env file that sets a variable per line:
REACT_APP_API_URL=http://api.example.com
REACT_APP_CLIENT_ID=XyzxYzxyZTwo versions of variables are supported. In addition to compile-time variables applied during build the app supports variables set at runtime, applied as each web dyno starts-up.
Requirement Compile-time Runtime never changes for a build β support for continuous delivery β updates immediately when setting new config vars β different values for staging & production (in a pipeline) β ex:REACT_APP_BUILD_VERSION (static fact about the bundle)
β
ex: REACT_APP_DEBUG_ASSERTIONS (prune code from bundle)
β
ex: REACT_APP_API_URL (transient, external reference)
β
ex: REACT_APP_FILEPICKER_API_KEY (Add-on config vars)
β
Supports REACT_APP_, NODE_, NPM_, & HEROKU_ prefixed variables.
Use Node's process.env object.
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<code>Runtime env var example: { process.env.REACT_APP_HELLO }</code>
);
}
}β»οΈ The app must be re-deployed for compiled changes to take effect, because during the build, these references will be replaced with their quoted string value.
heroku config:set REACT_APP_HELLO='I love sushi!'
git commit --allow-empty -m "Set REACT_APP_HELLO config var"
git push heroku masterOnly REACT_APP_ vars are replaced in create-react-app's build. To make any other variables visible to React, they must be prefixed for the build command in package.json, like this:
REACT_APP_HEROKU_SLUG_COMMIT=$HEROKU_SLUG_COMMIT react-scripts buildSupports only REACT_APP_ prefixed variables.
π«π€ Not for secrets. These values may be accessed by anyone who can see the React app.
Install the runtime env npm package:
npm install @mars/heroku-js-runtime-env --saveThen, require/import it to use the vars within components:
import React, { Component } from 'react';
import runtimeEnv from '@mars/heroku-js-runtime-env';
class App extends Component {
render() {
// Load the env object.
const env = runtimeEnv();
// β¦then use values just like `process.env`
return (
<code>Runtime env var example: { env.REACT_APP_HELLO }</code>
);
}
}β οΈ Avoid setting backslash escape sequences, such as \n, into Runtime config vars. Use literal UTF-8 values only; they will be automatically escaped.
If the javascript bundle location is customized, such as with an ejected created-react-app project, then the runtime may not be able to locate the bundle to inject runtime variables.
To solve this so the runtime can locate the bundle, set the custom bundle path:
heroku config:set JS_RUNTIME_TARGET_BUNDLE=/app/my/custom/path/js/*.jsβ³οΈ Note this path is a * glob, selecting multiple files, because as of create-react-app version 2 the bundle is split.
To unset this config and use the default path for create-react-app's bundle, /app/build/static/js/*.js:
heroku config:unset JS_RUNTIME_TARGET_BUNDLEπ«π€ Be careful not to export secrets. These values may be accessed by anyone who can see the React app.
Use a custom .profile.d script to make variables set by other components available to the React app by prefixing them with REACT_APP_.
create .profile.d/000-react-app-exports.sh
make it executable chmod +x .profile.d/000-react-app-exports.sh
add an export line for each variable:
export REACT_APP_ADDON_CONFIG=${ADDON_CONFIG:-}set-up & use Runtime configuration to access the variables
For example, to use the API key for the Filestack JS image uploader:
export REACT_APP_FILEPICKER_API_KEY=${FILEPICKER_API_KEY:-}Private modules are supported during build.
Setup your app with a .npmrc file following npm's guide for CI/deployment.
Set your secret in the NPM_TOKEN config var:
heroku config:set NPM_TOKEN=xxxxxConfirm that your app is using this buildpack:
heroku buildpacksIf it's not using create-react-app-buildpack, then set it:
heroku buildpacks:set mars/create-react-appβ¦and deploy with the new buildpack:
git commit --allow-empty -m 'Switch to create-react-app-buildpack'
git push heroku masterIf the error still occurs, then at least we know it's really using this buildpack! Proceed with troubleshooting.
Check this README to see if it already mentions the issue.
Search our issues to see if someone else has experienced the same problem.
Search the internet for mentions of the error message and its subject module, e.g. ENOENT "node-sass"
File a new issue. Please include:
This buildpack will never intentionally cause previously deployed apps to become undeployable. Using master as directed in the main instructions will always deploy an app with the most recent version of this buildpack.
Releases are tagged, so you can lock an app to a specific version, if that kind of determinism pleases you:
heroku buildpacks:set https://github.com/mars/create-react-app-buildpack.git#v6.0.0βοΈ Replace v6.0.0 with the desired release tag.
β»οΈ Then, commit & deploy to rebuild on the new buildpack version.
This buildpack combines several buildpacks, specified in .buildpacks, to support zero-configuration deployment on Heroku:
heroku/nodejs buildpack
node, puts on the $PATH
package.json, engines.node
node_modules/ cached between deploymentsNODE_ENV at buildtime:
NODE_ENV=development to install the build tooling of create-react-app's dev dependencies, like react-scripts
NODE_ENV, like NODE_ENV=test for automated testing in bin/test
NODE_ENV=production to be development to ensure dev dependencies are available for buildmars/create-react-app-inner-buildpack
react-scripts build
REACT_APP_, NODE_, NPM_, & HEROKU_ prefixed env vars to the build scriptNODE_ENV settingstatic.json already existsheroku/static buildpack
static.json (see also all static web server config)π The runtime web process is the last buildpack's default processes. heroku-buildpack-static uses bin/boot to launch its Nginx web server. Processes may be customized by committing a Procfile to the app.
Some kind feedback pointed out that this buildpack is not necessarily specific to create-react-app.
This buildpack can deploy any SPA [single-page app] as long as it meets the following requirements:
npm run build performs the transpile/bundlingbuild/index.html or the root specified in static.json exists at runtime.For new applications:
For existing applications: