← All writing

Deploy Build-Only React Apps to Heroku

Serve a production React build with a small Node.js application and deploy it to Heroku.

  • Web Development
  • DevOps

Today I had to deploy a React application to Heroku. I tried several methods and one of them required that I deploy the entire codebase, since Heroku would need the package.json for a successful build. That file is usually not included after running npm run build on a React application created using Create React App.

By using a simple Node.js app, I was able to serve the React build-only app and afterwards deploy it to Heroku. The result: faster deployment, with only the production React app found in production.

Here is how I did it

Note: This article applies when you want to deploy build-only React apps to Heroku. It assumes that you have a React app and a Heroku account.

Run the following command on your Create React App project to get a shiny build folder containing the production application:

npm run build

Create a new folder (or project) and initialize it with npm:

npm init -y

Next, copy the build folder into the new folder.

Now we need to create our Node server to serve the build files. Create a file named app.js and include the following code:

const express = require("express");
const path = require("path");

const app = express();
const port = process.env.PORT || 3000;

app.use(express.static(path.join(__dirname, "build")));

app.listen(port, () => console.log(`App is live on port ${port}!`));

Update: Don’t forget to install Express with npm i --save express. Also add the start script to package.json: "start": "node app". (Credit: Riste.)

This is all we need to serve the app. Run:

node app

Your terminal should start the app. View the result in your browser at http://localhost:3000.

Deploying to Heroku

The rest of the work will be done using the command-line interface, from the root of your Node.js app.

First, initialize the app with Git:

git init

Commit all files in the root directory by running:

git add .

Update: Don’t forget to add node_modules to .gitignore.

git commit -m "Initial commit"

Great job so far!

Now log in to Heroku. Ensure that you have the Heroku CLI installed.

heroku login

Once you are logged in, create a new project on Heroku. I’ll name mine reactapp. If that name is unavailable, use another name.

heroku create reactapp

Running the command above adds a new remote to your Git project. You can verify it with git remote -v.

Now deploy to the newly created Heroku project:

git push heroku master

If you don’t get any errors, your app should now be hosted on Heroku. Enter heroku open to view it in your browser.

That’s it, fellas! Share and connect with me on Twitter.

P.S. Check out create-react-app-buildpack if you prefer to deploy using a buildpack.

This post is also available on DEV.