How to deploy MERN stack to Heroku

  • put your react app in client folder(if you haven’t create react app)
  • create server.js and connect with db (like mongodb atlas)
  • create routes and port in server.js (express mongoose fast code)
  • prepare heroku port
let port = process.env.PORT;
if (port == null || port == "") {
port = 9000;
}
app.listen(port, () => {
console.log(`Server started on port`);
});
  • use react static file when process.env.NODE_ENV === ‘production’

we haven’t create build folder. In the next step write script in package.json to auto create build folder when deploy our app to heroku

const path = require('path');

if(process.env.NODE_ENV === 'production'){
app.use(express.static('client/build'));
})
}
  • to create auto build in react app
"scripts": {
"build": "cd client && npm run build",
"install-client": "cd client && npm install",
"heroku-postbuild": "npm run install-client && npm run build",

"start": "node server.js",
"server": "nodemon server.js",
"client": "cd client && npm start",
"dev": "concurrently \"npm run client\" \"npm run server\""
},

heroku-postbuild script will run install-client script (go to client and install the npm package that require) and will run build script (that script will go to client folder and create build folder in react app). Previous step is use the static file that is in the build folder.

  • add engine in server package.json

Check your node version with (node — version)

"engines": {
"node": "12.18.3"
},
  • go to your client folder and remove .git
  • git init
git init
git add .
git commit -m "first commit"
  • creating heroku git remote
heroku login
heroku create my-app
heroku git:remote -a my-app
  • create .gitignore file
/node_modules
npm-debug.log
.DS_Store
/*.env
  • run your app locally
heroku local

In deploy section of your heroku app, you will see deploy your application section

Now you are ready to deploy your app

git add .
git commit -m "second commit"
git push heroku master

--

--

Learning javascript and web-development

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store