How to setup a React app with Node backend—Heroku

How to setup a React app with Node backend—Heroku

In a previous article, we talked about how to set up for development; in this article, we will discuss how to set up for a production environment(Heroku).

Prerequisites

  • This article builds on the sample app built on the preceding article referenced above. To follow through, clone the app here.
  • Previous experience deploying a node app with Heroku CLI is needed. You can find a short article on that here

Introduction

To set up for development we had two different servers running; one to serve the React app and another for the backend. On Heroku, we will only need the backend server running. The same server will be used to serve the front end(React). The steps to be followed are:

  • Edit app.js to serve the React build
  • Add Heroku start scripts
  • Deploy!

Simple right? Let's get started.

Edit app.js

Add this to app.js, after other API endpoints :

// app.js 
if (process.env.NODE_ENV === 'production'){
    app.use(express.static('client/build'));
    const path = require('path');
    app.get('*', (req, res) => {
    res.sendFile(path.resolve('client', 'build', 'index.html'));
  });
}
[...]

In the code snippet, you set Express to use the folder client/build for static files. The GET endpoint with a wild card sends the index.html file as a response if no /API/* endpoint is hit.

Add Heroku start scripts

Add the following scripts to package.json:

/* package.json */
"scripts" : 
{
   [...]
    "client-build": "cd client && npm run build",
    "install-client": "cd client && npm install",
    "heroku-postbuild": "npm run install-client && npm run client-build",
    "start": "node app.js",
}

To explain the scripts in order of execution:

  1. start: Heroku uses this to start the app
  2. heroku-postbuild: This is not a random name but a name required by Heroku. The script runs after the node app has been built as the name implies. The script runs the other two scripts below.
  3. install-client: This script changes directory into the React app(client) and installs all dependencies.
  4. client-build: This script changes directory again into the client folder and creates the create-react-app build.

That gets us ready for deploying.

Deploy!

We will be using Heroku CLI to deploy to Heroku.

Heroku deployment depends on git as a version control system

Create an app on Heroku:

$ heroku create

This creates a remote repo named heroku

Push the master branch of the app to the heroku remote:

$ git push heroku master

This completes deployment and you should see the app build running and a build-complete message.

You can see the app up in the Heroku generated URL or open it from the command line:

$ heroku open

Finally, the code for this article can be found here .

Thanks for reading, make sure to like, clap, and follow this blog.