Heroku, a popular cloud platform as a service (PaaS), offers a simple and dynamic environment for hosting web applications. Deploying a React application on Heroku is a relatively straightforward process, even for those who are new to web development. In this guide, we will walk you through the steps involved in deploying a React application on Heroku.
Prerequisites
Before we begin, ensure that you have the following tools and accounts set up:
- Node.js and npm installed on your machine
- A Heroku account
- Heroku CLI installed on your system
- Git installed on your machine
Step 1: Setting up Your React Application
- Create a React App If you don’t already have a React app to deploy, you can create one using the Create React App (CRA) tool. Run the following command in your terminal:
npx create-react-app react-heroku-app
- Navigate to Your App Directory Move to your React app directory using the following command:
cd react-heroku-app
Step 2: Initializing a Git Repository
If your project is not already a Git repository, initialize it with the following commands:
git init git add . git commit -m "Initial commit"
Step 3: Creating a Heroku Application
- Login to Heroku Log in to your Heroku account through the CLI using the following command:
heroku login
- Create a Heroku App Create a new application on Heroku:
heroku create your-react-app-name
Step 4: Setting up the Heroku Buildpack
Heroku needs to know how to handle your React application. Add a buildpack for create-react-app using the following command:
heroku buildpacks:add mars/create-react-app
Step 5: Preparing the React App for Deployment
- Add a Start Script In your
package.json
file, add a start script to serve your app using a static server. Here’s an example using theserve
package:
"scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "heroku-postbuild": "npm install -g serve && serve -s build" },
- Install Serve Install the
serve
package to serve your app:
npm install serve
Step 6: Deploying the React App to Heroku
- Add and Commit Changes Commit all the changes you’ve made:
git add . git commit -m "Preparing for Heroku deployment"
- Push to Heroku Deploy your application to Heroku:
git push heroku master
Step 7: Opening the Deployed Application
Once the deployment process completes, open your application in a web browser using the following command:
heroku open
Your React application should now be live on Heroku!
Conclusion
Deploying a React application on Heroku is a straightforward process that involves setting up your React application, initializing a git repository, creating a Heroku application, and preparing and deploying your app to Heroku. We hope this guide helps you successfully deploy your React application on Heroku with ease. Happy coding!