Search code examples
reactjsazuredeploymentmern

A way to deploy a MERN app to Azure instead of Heroku


I was wondering how to deploy my mern app to Azure. I've been googling for days and it got me really frustrated. When I build my app it obviously only builds the client side. How can I upload my whole project to Azure and run the client side as well as the server side of the app?

I'd like to avoid Heroku and directly run my project from Azure.

Are there any tools I can use for the build?

Many thanks in advance!


Solution

  • In order to make a MERN app work on Azure, you have to configure your app to display your static react build through express.

    Edit your express server.js and add this:

    const path = require("path"); // on top
    
    // Serve Static assests if in production
    if (process.env.NODE_ENV === "production") {
      app.use(express.static("client/build")); // change this if your dir structure is different
      app.get("*", (req, res) => {
        res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
      });
    }
    

    Then, add this script line to your express package.json:

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

    Note: Edit this to meet your directory structure.

    That's it, now upload your app to Azure and set your express port to 80 in the environment vars in your Azure application settings.