DEV Community

mrcflorian
mrcflorian

Posted on • Updated on

How to Deploy a React app to Heroku

Deploying a React app to Heroku is a straightforward process. Below is a step-by-step guide:

Prerequisites:

  1. Ensure you have Git installed.
  2. Ensure you have a Heroku account. If not, sign up here.
  3. Install the Heroku CLI.

You can skip all this with the power of AI now - check out Deltoid.

Steps to Deploy:

Initialize a Git Repository (If it's not already a Git repository)

   git init
Enter fullscreen mode Exit fullscreen mode

Commit Your Code:
If you haven't committed your React app to git yet, you can do so with the following commands:

   git add .
   git commit -m "Initial commit"
Enter fullscreen mode Exit fullscreen mode

Create a Heroku App:

   heroku login
   heroku create <optional-name-of-your-app>
Enter fullscreen mode Exit fullscreen mode

Use a Static Server:
Since a React app consists of static files when built, you will need a server to serve these files. One popular option is the serve package.

Install serve:

   npm install serve --save
Enter fullscreen mode Exit fullscreen mode

Modify your scripts section in package.json:

   "scripts": {
     "start": "serve -s build",
     "build": "react-scripts build",
     "dev": "react-scripts start",
     ...
   }
Enter fullscreen mode Exit fullscreen mode

The above configuration will serve your build directory when you run npm start.

Set Up Node.js Server:
For Heroku to recognize the app as a Node.js app, you should have both package.json and a Procfile at the root of your project.

Create a Procfile (no file extension) in the root directory and add the following line:

   web: npm start
Enter fullscreen mode Exit fullscreen mode

Update .gitignore:
Ensure you're not excluding the build directory in your .gitignore. Heroku needs this to serve your app.

Build Your App:

   npm run build
Enter fullscreen mode Exit fullscreen mode

Commit the Build:

   git add .
   git commit -m "Prepare for Heroku deployment"
Enter fullscreen mode Exit fullscreen mode

Push to Heroku:

   git push heroku master
Enter fullscreen mode Exit fullscreen mode

Open Your App in the Browser:
Once the deployment process completes, you can view your app in the browser:

   heroku open
Enter fullscreen mode Exit fullscreen mode

That's it! Your React app should now be live on Heroku. Remember that whenever you make changes to your React app, you'll need to rebuild and push to Heroku again.

Check out Dopebase Tutorials for more tech articles.

Top comments (0)