How To Deploy MERN App on Heroku

How To Deploy MERN App on Heroku

How To Deploy MERN App on Heroku

Building a MERN (MongoDB, Express, React, Node.js) application is an exciting journey, but once your app is ready, deployment becomes the next big step. Deploying your MERN app on Heroku allows you to showcase your project to the world --- whether it's a startup MVP, a business tool, or a client project. In this guide, we'll go step-by-step through how to deploy a MERN stack app to Heroku, ensuring everything runs smoothly on both frontend and backend.

What is the MERN Stack?

Before MERN Stack Development we dive into deployment, let's quickly recap what the MERN stack is. MERN stands for:

  • MongoDB: A NoSQL database used for storing data in flexible, JSON-like documents.
  • Express.js: A lightweight backend web application framework that runs on Node.js.
  • React.js: A frontend JavaScript library for building interactive user interfaces.
  • Node.js: A runtime environment for executing JavaScript code on the server side.

Together, these technologies form a full-stack JavaScript framework that allows developers to build fast, scalable, and dynamic web applications.

If you're new to full-stack development, it's highly recommended to learn how these technologies interact before deploying. Once your app is running smoothly locally, you can proceed with deployment.

Why Choose Heroku for MERN Deployment?

Heroku is a Platform as a Service (PaaS) that simplifies web app deployment. It supports multiple programming languages including Node.js, Python, Ruby, and more. For MERN developers, Heroku offers a seamless experience with built-in Git integration, easy scaling, and add-ons for databases like MongoDB Atlas.

Benefits of Using Heroku

  • Ease of deployment: You can deploy directly from GitHub or Git.
  • Scalability: Scale your app as it grows.
  • Integration: Compatible with MongoDB Atlas and other cloud services.
  • Free tier: Great for testing or small-scale projects.

Now, let's move on to how you can actually deploy your MERN app to Heroku.

Step 1: Prepare Your Project for Deployment

Before pushing anything to Heroku, you need to prepare your project properly.

1.1 Combine the Client and Server

In development, the React app (frontend) and Node/Express app (backend) usually run separately --- one with npm start in /client and the other in /server. For deployment, you need to make sure both are part of one integrated app.

Here's how you can structure your project:

/root
  ├── client/        # React frontend
  ├── server.js      # Express backend
  ├── package.json
  └── .gitignore

1.2 Add a Build Script

Inside your root package.json, you'll need to ensure that your build script runs properly. You can add the following line to the "scripts" section:

"scripts": {
  "start": "node server.js",
  "heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
}

The heroku-postbuild command ensures Heroku installs dependencies for your React app and builds it before deployment.

Step 2: Serve the React Frontend from Express

In your backend (server.js), you'll serve the built React files. Replace your development routes with something like this:

const express = require('express');
const path = require('path');
const app = express();

app.use(express.json());

// Serve static files from the React app
app.use(express.static(path.join(__dirname, 'client/build')));

// API routes
app.get('/api', (req, res) => {
  res.json({ message: 'API running successfully' });
});

// Handle React routing, return all requests to React app
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

This setup ensures that your backend serves both API requests and the frontend React app.

Step 3: Connect MongoDB Atlas

Heroku doesn't host databases, so you'll need to use MongoDB Atlas, a free cloud database service provided by MongoDB.

Steps to Connect:

  1. Go to MongoDB Atlas.
  2. Create a new cluster (the free tier works fine).
  3. Whitelist all IP addresses (0.0.0.0/0).
  4. Get your connection string from the "Connect" section.
  5. Store it in your environment variable (we'll handle that in the next step).

In your code, you can connect to MongoDB Atlas like this:

const mongoose = require('mongoose');
const mongoURI = process.env.MONGO_URI;

mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('MongoDB connected'))
  .catch(err => console.error(err));

Step 4: Create a Heroku Account and Install Heroku CLI

If you don't have one already, sign up at Heroku. Then install the Heroku CLI on your computer.

To verify the installation, run:

heroku --version

If it returns a version number, the CLI is installed correctly.

Step 5: Initialize Git and Push to Heroku

Make sure your project is initialized as a Git repository. If not, run:

git init
git add .
git commit -m "Initial commit"

Then log into Heroku:

heroku login

Once logged in, create a new Heroku app:

heroku create your-app-name

This will create a remote repository on Heroku. To deploy your app, push your code to that repository:

git push heroku main

If your branch is master, use git push heroku master instead.

Heroku will automatically detect your Node.js environment and run the necessary build commands.

Step 6: Set Environment Variables

Your MongoDB connection string and other sensitive data shouldn't be hardcoded. Instead, use environment variables.

You can set environment variables using:

heroku config:set MONGO_URI="your_mongodb_connection_string"

You can view them anytime by running:

heroku config

Step 7: Test the Deployment

After pushing your code, open your deployed app using:

heroku open

Your React frontend should load, and your backend APIs should function correctly. Check logs for any errors using:

heroku logs --tail

This command helps you debug any runtime issues.

Step 8: Deploy via GitHub (Optional)

You can also link your GitHub repository to Heroku for automated deployments.

  1. Go to your Heroku Dashboard.
  2. Open your app > "Deploy" tab.
  3. Under "Deployment method," select GitHub.
  4. Connect your repository.
  5. Enable Automatic Deploys for continuous integration.

Whenever you push updates to your GitHub branch, Heroku will automatically redeploy your app.

Step 9: Common Deployment Issues and Fixes

Even experienced developers face deployment challenges. Let's cover a few common ones:

9.1 Missing Dependencies

If your React build fails, make sure all dependencies are installed correctly:

npm install
npm install --prefix client

9.2 Build Fails on Heroku

Ensure your heroku-postbuild script is added correctly to package.json and you're using the right Node version in your engines:

"engines": {
  "node": "20.x"
}

9.3 MongoDB Connection Issues

If your app can't connect to MongoDB, double-check your connection string and environment variables. Make sure your MongoDB cluster is set to allow external connections.

9.4 Static Files Not Loading

Ensure your Express static file path points correctly to the client/build directory.

Step 10: Scaling and Monitoring Your App

Once deployed, Heroku allows you to easily scale and monitor your app.

Scaling Dynos

Dynos are Heroku's lightweight containers. You can scale your app using:

heroku ps:scale web=1

Upgrade your plan or add more dynos as your user base grows.

Add-ons and Monitoring

Heroku provides add-ons for logging, monitoring, and caching. Some popular ones include:

  • Papertrail: For viewing logs in real time.
  • New Relic: For performance monitoring.
  • Redis: For caching and session management.

Step 11: Updating Your Deployed App

To deploy changes, simply commit and push to Heroku again:

git add .
git commit -m "Updated frontend and API routes"
git push heroku main

Heroku will rebuild and redeploy automatically.

Step 12: Best Practices for MERN Deployment

To ensure your app performs optimally, follow these tips:

  • Use .env files locally and heroku config in production.
  • Optimize your React build for performance.
  • Use gzip compression in Express.
  • Enable HTTPS redirection.
  • Monitor app performance through logs and metrics.

Conclusion

Deploying a MERN app on Heroku might seem challenging at first, but following the right steps makes the process smooth and predictable. Heroku's simple interface, Git integration, and compatibility with MongoDB Atlas make it one of the best options for full-stack JavaScript developers.

If you're building a production-grade MERN application and want expert guidance, hire AAMAX --- a full-service digital marketing company offering Web Development, MERN Stack Development, SEO, and Digital Marketing services. Our team can help you design, develop, and deploy scalable web apps that perform seamlessly across devices and platforms.

With proper configuration and attention to best practices, your MERN app can run efficiently on Heroku --- ready to serve users globally.

Related Blogs

How To Deploy MERN App on Netlify

How To Deploy MERN App on Netlify

Deploying a MERN (MongoDB, Express.js, React, Node.js) application can be a challenging task for many developers, especially when it comes to choosing...

How To Learn React JS

How To Learn React JS

React JS has revolutionized front-end web development with its component-based architecture, virtual DOM, and vast ecosystem. Whether you’re a beginne...

How To Deploy MERN App on Heroku

How To Deploy MERN App on Heroku

MERN (MongoDB, Express, React, Node.js) application is an exciting journey, but once your app is ready, deployment becomes the next big step. Deployin...

How To Host MERN Stack Website

How To Host MERN Stack Website

Hosting a MERN stack website — which combines MongoDB, Express.js, React, and Node.js — can seem intimidating at first, especially if you’re new to fu...

How To Push MERN Stack Project on Github

How To Push MERN Stack Project on Github

Pushing your MERN Stack project (MongoDB, Express.js, React, and Node.js) to GitHub is one of the most essential steps in modern web development. It a...

How To Use React JS

How To Use React JS

React JS has revolutionized front-end development by enabling developers to create fast, dynamic, and interactive user interfaces with ease.

Need Help? Chat with Our AI Support Bot