How to deploy mern app to heroku
Heroku is a powerful cloud platform that makes deploying and managing web applications remarkably easy. Its seamless support for Node.js, along with its free tier for basic apps, makes Heroku a popular choice for deploying MERN stack applications. In this guide, we’ll walk you through the steps of deploying your MERN app to Heroku.
Prerequisites
Before you begin, ensure you have the following:
- A free Heroku account (https://signup.heroku.com/)
- The Heroku CLI installed (https://devcenter.heroku.com/articles/heroku-cli)
- A ready-to-deploy MERN application (both backend and frontend code).
- Git is installed, and your project is under Git version control.
Steps for Deployment
1. Prepare Your Backend for Deployment
- Production Build (React): In your React project’s directory (usually client), create an optimized production build using:
- Bash
- npm run build
- Use code with caution.
- content_copy
- Server Configuration: Verify that your Express server is set up to serve the static files created by your React build. Here’s a common way to do this:
- JavaScript
- // In your server’s index.js or main server file
- const path = require(‘path’);
- app.use(express.static(path.join(__dirname, ‘client’, ‘build’)));
- // … other server code
- Start Script: Add a “start” script in your backend’s package.json to tell Heroku how to launch your server (e.g., “start”: “node index.js”)
2. Create a Heroku App
- Login: Open a terminal and log in to your Heroku account:
- Bash
- heroku login
- Create App: Give your app a unique name:
- Bash
- heroku create <your-unique-app-name>
3. Database Setup (If Needed)
- MongoDB: If your app uses MongoDB, add a database instance. Heroku offers add-ons like MongoDB Atlas (which usually has a free tier). Follow the instructions for the chosen add-on to provision your database.
- Environment Variables: Set your MongoDB connection string in Heroku’s app settings under “Config Vars.”
4. Git Deployment
- Initialize Git (if needed): Use git init within your project’s root directory.
- Add Heroku Remote:
- Bash
- heroku git:remote -a <your-unique-app-name>
- Push Code:
- Bash
- git add .
- git commit -m “Ready for Heroku deployment”
- git push heroku master
Testing and Troubleshooting
- Open Your App: Visit https://your-unique-app-name.herokuapp.com to see your deployed MERN application.
- Check Logs: Use the Heroku CLI command heroku logs to debug any issues during the deployment process.
Recent Posts