Search code examples
node.jsreactjsdeploymentweb-deploymentmern

Not able to prepare my MERN app for deployment


I have never deployed a MERN app to production before. This is going to be my first attempt and I am planning to deploy the app to digital ocean.

So, I have prepared my MERN app for deployment by following the instructions in a Udemy course. My app structure is as follows: enter image description here The following are the main changes that I have made to my application:

  1. Because there will be no server created by create-react-app in production, I have written the production routing logic inside server/index.js that essentially says that for any routes not managed by app.use("/api/users", userRoutes) & app.use("/api/download", downloadRoutes), the backend server will server the index.html file inside the client/build folder, which I have created by running the command: npm run build.

server/index.js

const express = require("express");
const path = require("path");
const dotenv = require("dotenv");
const colors = require("colors");
const connectDB = require("./config/db");
const {
  notFound,
  globalErrorHandler,
} = require("./middleware/errorMiddleware");
const userRoutes = require("./routes/userRoutes");
const downloadRoutes = require("./routes/downloadRoutes");

dotenv.config();

connectDB();

const app = express();

app.use(express.json());

app.use("/api/users", userRoutes);
app.use("/api/download", downloadRoutes);

// Routing logic in production

if (process.env.NODE_ENV === "production") {
  app.use(express.static(path.join(__dirname, "/client/build")));

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

app.use(notFound);
app.use(globalErrorHandler);

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`.yellow.bold);
});

  1. I have changed the process.env.NODE_ENV to production inside the .env file.

After the above-mentioned changes, when I run "npm start" (starts only the backend server) (not "npm run dev" that concurrently starts both the frontend and backend server) and visit http://localhost:5000, I should see my app. Instead, I see the following error.

enter image description here What am I doing wrong?


Solution

  • As you can see in the error message, Express is looking for an index.html inside server/client/build which does not exist. Fix the path.

    app.use(express.static(path.join(__dirname, '../client/build')))