MERN Stack - Authentication and Deployment - Part 3/3

Fri Nov 05 2021

This is the final part of MERN Stack Authentication and Deployment series. We have already built our backend in part 1 and react app in part 2. In this final part, we will deploy our MERN stack app to heroku.

Make sure you have heroku cli installed

npm install -g heroku

You need have an account on heroku

Before we deploy our app, we have to make some changes in backend. In index.js at the top paste this

const path = require("path")

and after app.use("/auth", require("./routes/user")) paste the following

// Serve build
if (process.env.NODE_ENV === "production") {

  app.get("*", (req, res) => {
    res.sendFile(path.resolve(__dirname, "client", "build", "index.html"))

Here we are checking if the environment is production then we will serve build folder which will be in client directory. After that we provided the path to the file which will be served which is index.html. Open backend's package.json file and inside scripts add

"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"

Now we will login to heroku using terminal. Open terminal and

heroku login

Once we are logged in, now its time to create app. In terminal run

heroku create <OPTIONAL-your-app-name>

If you provide app name heroku will create app with that name if the name is not already taken by someone else. If you don't provide app name, heroku will give it a random name. Go to you will see the app you just created. While you are at heroku dashboard click on your app then click Settings click Reveal Config Vars and copy paste key values from your project's .env file.

Now we will create git repository. Before that remove the client side repository if it exists. In terminal navigate into client directory and run

rm -rf .git

In terminal go back to root directory and run

git init

Once git is initialized we will link it to heroku

heroku git:remote -a <app-name>

Finally we add commit and push to heroku

git add .
git commit -m "initial commit"
git push origin master

It will take some time to deploy once its done from your heroku dashboad click Open app and you will see your site live on heroku.


Privacy Policy

Developed By Farhan Farooq