Developing a MERN (MongoDB, Express.js, React, and Node.js) Project (Part 1)

Hi everyone, I will publish my personal notes on how to develop a web app by using MERN (MongoDB, Express. js, React, and Node. js) stack from scratch. I’ll go step by step and explain what and how I did. Let’s get going.

The tech stack that I am planning to use for this project is explained below. Things might change as I proceed. If that is the case, I will update my list.

BACKEND:

Node.js with Express.js: For backend server development, routing, middleware handling, and request processing. (Easier for developers, a popular choice with a vast community, scalable, -express.js- a minimalist web framework that simplifies routing, middleware, and request handling)

MongoDB: Is a good option as a NoSQL database for storing restaurant menus, customer orders, and related data. (flexible and scalable, stores data in JSON-like documents, making it easier to work with data in your JavaScript-based application, a large and active community)

FRONTEND:

React.js: For building interactive and dynamic user interfaces for restaurant customers to view menus, place orders, and make payments. (declarative approach makes it easier to build interactive UIs, component-based architecture that ensures reusability and maintainability, a vast ecosystem of libraries and tools, active community)

INITIAL FOLDER STRUCTURE:

I will store all project files and folders in a directory named “menu_haus”. It will initially have two subfolders. “frontend” is the folder where all frontend files and folders will be stored (we can also call it “client” side), and “backend” is the folder where all backend files and folders will be stored (we can also call it “server” side).

Code Editor:

I will be using VS Code as code editor/terminal. You can download it from here or use the editor of your own choosing.

Installing Node.js

First thing first. If you don’t have node.js installed in your computer, you need to install it first.

Head over to the official Node.js website. Click on the “Download” button and choose the appropriate installer for your operating system (Windows, macOS, or Linux). Once downloaded, double-click the installer file and follow the on-screen instructions. The installation process is usually straightforward and only takes a few minutes. After installation process is finished, open a terminal or command prompt and type the following command:

npm -v

If npm is installed correctly, you should see the version number displayed in the terminal as seen below. The version might be different, as new versions are rolled out over time.

10.2.5

Now let’s start building.

We open up a new terminal in VS Code, navigate to the “main_haus” folder and run the command below to initialize a new Node.js:

npm init -y

This command basically creates a “package.json” file in the folder with the default info for the new project. Here is how it looks like:

{
  "name": "menu_haus",  // menu_haus is automatically chosen from the folder name
  "version": "1.0.0",   // Initial version number
  "description": "",    // Empty initially
  "main": "index.js",   // Default entry point for your code
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"      // A permissive open-source license
}

I will make a small modification to the file and delete the “test” part, define the start point for the backend server and desribe a type (how we import modules). Here is the modified version:

{
  "name": "menu_haus",  // menu_haus is automatically chosen from the folder name
  "version": "1.0.0",   // Initial version number
  "description": "",    // Empty initially
  "main": "index.js",   // Default entry point for your code
  "type": "module",
  "scripts": {
    "server": "node backend/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"      // A permissive open-source license
}

FRONTEND SETUP

Next, we create the frontend side of our wep app by running this command in the terminal.

 npx create-react-app frontend

This code basically creates a “frontend” folder and installed a React app inside it. The React app comes with several files and folders. Namely, “public” and “src” (short for source) folders, and “package.json” and “package-lock.json” files are created.

Now, let’s check whether the front-end is running without issues.

We navigate to the “frontend” folder, and start the Frontend Server by running this command in the terminal:

npm run start

If everything is setup properly. A new tab should be opened in your web browser and automatically navigate to http://localhost:3000 in which the React application will load as seen in the screenshot. If the page is not loaded automatically, you can open a browser and navigate to “http://localhost:3000” yourself.

Here is the current folder structure we see in our “frontend” folder:

menu_haus
└── frontend
    ├── node_modules
    ├── public
    ├── src
    ├── package-lock.json
    └── package.json

Explanation of Frontend Folder Structure:

When we initialize a new React app as we explained above, it generates the set of default files and folders to help us get started with our project.

“public” Folder: The public folder contains static assets that are served to the client without being processed by Webpack. We generally won’t need to make many changes to the files inside the “public” folder. However, we might modify “index.html” to include additional meta tags, change the title of our application, or add other external scripts if necessary.

Here’s what you’ll typically find in the public folder:

  • index.html: This is the main HTML file that serves as the entry point for your React application. It contains a “<div id=”root”>” where our React app will be rendered.
  • Favicon, manifest, and other static assets: We can place favicon images, manifest.json files, or any other static assets that our application requires in this folder.

“src” Folder: The src folder contains the source code for our React application. We’ll spend most of our time working within the “src” folder.

Here’s what you’ll typically find in the src folder:

  • index.js: This is the JavaScript entry point for your React application. It renders the root component (App) into the DOM inside the index.html file. We will modify “index.js” if we need to perform additional setup or configuration for our React application.
  • App.js: This is the main component of our React application. It serves as the container for other components and defines the overall structure of your application. We will modify “App.js” to define the structure of our application and include other components.
  • Other Components: We can create additional components in separate files within the src folder. These components are typically imported and used inside App.js or other parent components.
  • CSS, SCSS, or other styling files: We can place CSS or SCSS files to style our components in this folder.
  • Other assets: We can place images, fonts, or other assets required by our application in this folder.

I explained the default files and folders that are generated when we installed the new React app in the “frontend” directory. We will, in some cases modify the default files and folders and mostly will add new ones as we continue to develop our own web app.

Now, let’s continue with the backend side.

BACKEND SETUP

We create a folder named “backend” (you can call it “server” too) inside “menu_haus” directory.

Setting Up Database Connection

We create a file named “db.js” inside backend folder to establish a connection to our MongoDB database using Mongoose. Here is the content of the “db.js” file.

import mongoose from "mongoose";

const connectToDatabase = async () => {
  try {
    mongoose.set("strictQuery", false);
    const connect = await mongoose.connect(process.env.MONGO_URI, {
      useUnifiedTopology: true,
      useNewUrlParser: true,
    });
    console.log(`MongoDb Connected: ${connect.connection.host}`);
  } catch (error) {
    console.log(`Error: ${error.message}`);
  }
};

export default connectToDatabase;

Next we create a .”env” file inside our root directory “menu_haus”. We will store sensitive information such as database connection information inside this code. Here is the content of the “.env” file:

MONGO_URI: mongodb://localhost:27017/menuhaus

Note 2: If you prefer to use MongoDB Atlas instead of using the local version, you need to open an account at the official MongoDB website and do the necessary configuration. (I won’t go into detail on how to do the configuration here for now.)

If you use MongoDB Atlas then the Mongo URI will be different, so will the “.env” file be:

MONGO_URI: mongodb+srv://<username>:<password>@<cluster>/<database>?retryWrites=true&w=majority

Here is the breakdown for the mongoURI:

<username>: Your MongoDB Atlas username
<password>: Your MongoDB Atlas password
<cluster>: The name of your MongoDB Atlas cluster
<database>: The name of the database you want to connect

Installing Dependencies

Next, we install the necessary dependencies by running the following command in the terminal while we are in the root directory (“menu_haus”):

npm install bcryptjs concurrently cors dotenv express express-async-handler jsonwebtoken jwt-decode mongoose nodemailer stripe

With this command, (1) a folder named “node_modules” has been created in the root folder and eleven modules have been downloaded and installed in that folder. (The number of modules we install depends on what we are trying to do. So These are some of the modules that you want to use for various projects.) (2) Also a file named “packages-lock.json” has been created. This file is automatically generated by npm when you install or update dependencies. It’s not intended for manual editing. (3) Also with the command, the package.json file which we created at the beginning has been updated and new dependencies are added to the file. Here is the updated package.json file:

{
  "name": "menu_haus",  // menu_haus is automatically chosen from the folder name
  "version": "1.0.0",   // Initial version number
  "description": "",    // Empty initially
  "main": "index.js",   // Default entry point for your code
  "type": "module",
  "scripts": {
    "server": "node backend/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "concurrently": "^8.2.2",
    "cors": "^2.8.5",
    "dotenv": "^16.4.1",
    "express": "^4.18.2",
    "express-async-handler": "^1.2.0",
    "jsonwebtoken": "^9.0.2",
    "jwt-decode": "^4.0.0",
    "mongoose": "^8.1.1",
    "nodemailer": "^6.9.8",
    "stripe": "^14.14.0"
  }
}

I’m especially going into some details to help us understand how the npm commands works.

Creating index.js for the Backend

Next, we create a “index.js” file inside the backend folder and paste the following content inside:

import dotenv from "dotenv";
dotenv.config();
import connectToDatabase from "./db.js";
import express from "express";
import cors from "cors";

connectToDatabase();
const app = express();
app.use(express.json());
app.use(cors());

const port = 5000;

app.get("/", (req, res) => {
    res.send("Api is running...");
})

app.listen(port, () => {
    console.log(`Server runs on port ${port}`);
});

MongoDB Installation

MongoDB can be used in two ways. You can either connect to MongoDB Atlas which is the cloud version provided by MongoDB, or you can install it locally. We’ll set up MongoDB on our machine. Once MongoDB is installed, we can establish a connection from our Express.js application to the MongoDB database using Mongoose, a MongoDB object modeling tool for Node.js.

Download: We first, download the appropriate version of MongoDB for our operating system (e.g., Windows, macOS, Linux) from here. Then we do the installation by following the instructions provided for our operating system. (For Windows, you can use the MongoDB installer wizard. For macOS and Linux, you can use package managers like Homebrew or apt-get.)

Start MongoDB service: Once MongoDB is installed, we start the MongoDB server. For most installations, you can start the MongoDB service using the following command in the terminal or command prompt:

mongod

Setup MongoDB Database and Collections (Optional): We can use the MongoDB shell to interact with your MongoDB instance directly. For that we open a new terminal or command prompt and run the following command to access the MongoDB shell:

(Note: All the database operations including creating a new database can be done directly with the scripts we will run in the backend later on. So we don’t need to setup the database or collections via the MongoDB shell.)

mongo

In the MongoDB shell, we can create a new database using the use command. For example:

use menuhaus

MongoDB collections are equivalent to tables in relational databases. You can create collections as needed for your application data.

We now have successfully completed the basic setup for the backend. Let’s checkout if we did everything right.

Navigate to “backend” folder if you are not already there and start the Backend Server by running this command in the terminal:

npm start

If you see “MongoDB connected” in the terminal, then everything looks good at the backend so far.

Finally here is the folder structure we see in our project directory:

menu_haus
└── backend
        db.js
        index.js
    frontend
    └── node_modules
        public
        src
        package-lock.json
        package.json 
    node_modules
    .env
    package-lock.json
    package.json

Let’s wrap up our tutorial for this part. We will continue with developing modules and other parts for both the backend and frontend in the following parts.

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir