How to Set Up MERN Stack Project for Beginners

Published by Pawan Sargar on

MERN Stack Project Setup

Working with Full Stack Web Development for the first time can be little complicated, as there are many technologies used behind the scenes. But, if you master the project setup, your development will be a lot easier.

Today, in this post you’ll learn how to set up the perfect MERN Stack Project, including folder structures, basic boilerplate code to get you started.

So, let’s get started!

MERN Stack Project Setup

#1 Directories

Create a folder at your desired path and name it something like “MERN-APP” or anything you wish. Now, get into that folder and create two more folders “Client” & “Server”. The client will contain the client-side of the app which is React & Server will contain the backend side which is Nodejs.

  • MERN-APP
    • Client
    • Server

This is what your project setup should look like now.

#2 Client & Server

Client –

Right-click on the Client and Server Folders and open them inside a Terminal side by side. On the Client side now you can create react app.

npx create-react-app .

or

yarn create react-app .

If you add a full stop after the command, your app will be created inside the same directory which is Client. After React is installed, install a package called Axios. It’s used to make asynchronous HTTP requests. This will help us to receive the data from backend.

npm i axios

or

yarn add axios

Server –

Now, on the Server side of the terminal, let’s create our main file which I prefer to name as index.js, because React will have an app.js file.

touch index.js

Let’s initialize NPM and install all required packages.

npm init

The above command will initialize the NPM, if you want to avoid the enter stuff, just add ” -y” after init.

Packages We’ll use,

  • express
  • mongoose
  • cors (important)
  • dotenv(optional)

These packages are required, if your app needs other packages, install them too.

npm i express mongoose cors dotenv

The above command will install all of the required packages for the backend.

Now, we’ve installed both Client and Server, let’s set up the boilerplate code, to connect our Frontend and Backend.

#3 Connecting Client & Server

Whenever starting a Fullstack project, I prefer starting out with the backend as then we can design the Frontend as per requirements.

Server –

This will be the folder structure of the server-side,

  • Server
    • Models(folder)
      • FriendModel.js
    • index.js(main file)

Models will contain all of the Mongoose Models, and you can even separate Routes & Controllers, but to keep it simple let’s stick to the main file. Though you can learn about it here.

This is the main file of the backend, here we’ve initialized all the required packages and middlewares and listened to port 3001, as React by default uses port 3000.

Note: Cors is important package, without it backend will not be able to connect with React.

const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");

const app = express();

//middlewares
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());

//connecting to local database
mongoose.connect("mongodb://localhost:27017/mern-app", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

//importing friend model
const FriendModel = require("./models/friends");

//read data route
app.get("/read", (req, res) => {
  FriendModel.find({}, (err, result) => {

    err ? res.send(err) : res.send(result);
  });
});

app.listen(3001 || process.env.PORT, () => {
  console.log("Server is running on port 3001!");
});

To summarize it, here we have created a get route, where blackened will make a GET request to the database to get the result(data) and finally sending it to the Frontend.

const mongoose = require("mongoose");

const friendSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    age: {
        type: Number,
        required: true
    },
    description: {
        type: String,
        required: true
    }
});

const FriendModel = mongoose.model("Friend", friendSchema);
module.exports = FriendModel;

Ok, so this is it for the backend, now let’s move to the frontend.

About Database –

As we are using MongoDB with Mongoose in this project, make sure that you have installed MongoDB locally in your system. If you don’t know how to do it, here’s the tutorial on how to install MongoDB locally.

I’ve already added dummy data to the database using Robo 3T. It helps us to use the database in the Graphical User interface.

Dummy Data:-

How to setup MERN Stack Project

Client –

Client-Side Folder Structure,

  • Client
    • Public(folder)
      • index.html
      • Assets(folder)
        • //contains images
    • src(folder)
      • App.css
      • App.jsx
      • Index.js
      • Components(folder)
        • //contains all component files

import React, { useEffect } from "react";
import Axios from "axios";
import "./styles.css";

function App() {
  //fetching data from database when document loads
  useEffect(() => {
    Axios.get("http://localhost:3001/read")
      .then((response) => console.log(response.data))
      .catch((err) => console.log(err));
  }, []);

  return (
    <>
      <h1>MERN Stack Project Setup</h1>
    </>
  );
}

export default App;

Here, it’s just the basic React imports and functional components, but we’re also using React Hook useEffect. This hook will fetch the data from the backend every time our document loads.

Now, if you check the console in the browser, you would have gotten an object with the data, as shown in the below image.

How to setup MERN Stack Project

So, this is how you set up a MERN Stack project, it’s simple but can be complicated for beginners. Though I’ve explained most of the bits and pieces, so you don’t need to worry about it, just follow this post whenever stuck.

I hope you liked it, if you did make sure to share it with your friends and also signup for our newsletter to never miss amazing posts on web development.

Pawan Sargar
Follow him
```html ```

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *