Today I had to deploy a React application to Heroku. I tried several methods and one of them required that I deployed the entire codebase since Heroku would need the package.json (for a successful build) which is usually not included after running npm run build
on a React application created using CRA.
By using a simple nodejs app, I was able to serve the react (build-only) app and afterwards, I deployed to Heroku. The result: Faster deployment, and only React production app is found in production.
Here is how I did it
Note: This article applies in the case where you want to deploy build-only react apps to Heroku. Hence, it is assumed that you have a react app and an account on heroku.
Run npm run build
on your CRA app to get a shiny build folder containing the production application.
Create a new folder (or project) and initialize it with npm.
npm init -y CLI
Next, Copy the build folder into the new folder (created above).
Now, we need to create our node server to serve the build files. We will do this by creating a file named app.js and include the following code block:
const express = require('express') const path = require('path'); const app = express() const port = process.env.PORT || 3000 // Heroku will need the PORT environment variable app.use(express.static(path.join(__dirname, 'build'))); app.listen(port, () => console.log( `App is live on port ${port}!` ))
Update: i)Don’t forget to install express using npm i –save express
ii) Also add the start script to package.json “start”:“node app”
(credit: Riste)
This is all we need to do to serve the app. Running
node appin your terminal should start the app. You can view the result in your browser by navigating to http://localhost:3000.
Deploying to Heroku
The rest of the work will be done using the command line interface (terminal/bash/cmd), and in the root of your nodejs app.First, we have to initialize our app with git
git init
Commit all files in the root directory by running commands in sequence
git add .Update: Don’t forget to add
node_modules
to .gitignore
git commit -m “Initial commit”
Great job so far!
Now login to heroku (ensure that you have 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
By running the command above, a new remote is added to your git project. You can verify by running the command git remote -v
.
We now have to deploy to the newly created heroku project
git push heroku master
If you don’t get any errors, you app should now be hosted on heroku.
Enter the following command to view it in your browser heroku open
.
That’s it fellas! Leave your comments, share and connect with me on Twitter
PS: Check out create-react-app-buildpack if you prefer to deploy using buildpack.