Today I had to deploy a React application to Heroku. I tried several methods – one of them required that I deploy 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, afterward, I deployed it to Heroku. The result: Faster deployment, and only the React production app is found in production.
Note: This shot applies to the case of when 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
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 can do this by creating a file named app.js and including 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:
npm i --save express
“start”:“node app”
(credit: Riste)This is all we need to do to serve the app. Running
node app.jsin your terminal should start the app. You can view the result in your browser by navigating to, .
The rest of the work will be done using the command-line interface (terminal/bash/cmd) 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 the following 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
Running the command above, adds a new remote to your git project. You can verify this by running, 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, your app will be hosted on Heroku.
Enter heroku open
to view it in your browser.
That’s it! Leave your comments, and share and connect with me on Twitter.
PS : Check out create-react-app-buildpack if you prefer to deploy using buildpack.
RELATED TAGS
CONTRIBUTOR
View all Courses