Open In App

MERN Stack

Last Updated : 13 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Web development refers to the creating, building, and maintaining of websites. It includes aspects such as web design, web publishing, web programming, and database management. One of the most famous stack that is used for Web Development is MERN stack. This stack provides an end-to-end framework for the developers to work in and each of these technologies play a big part in the development of web applications.

Roadmap-to-Mern-stack-developer-copy-(3)

What is MERN Stack?

MERN Stack is a JavaScript Stack that is used for easier and faster deployment of full-stack web applications. MERN Stack comprises of 4 technologies namely: MongoDB, Express, React and Node.js. It is designed to make the development process smoother and easier.

  • MongoDB: Non Relational Database
  • Express: Node.js web server
  • React: JavaScript Frontend Framework
  • Node: JavaScript Web Server

How MERN stack works?

When working with MERN stack, developers create implement View layer using React and Express and Node are used to implement application layer of website then MongoDB is used to implement database layer

How-MERN-Stack-Works-copy

How does MERN stack work?

Roadmap to become a MERN Stack Developer

Step 1: Learn basics of HTML, CSS and JavaScript

Step 2: Learn React which is a frontend library for building User Interfaces

Step 3: Learn Node.js which is JavaScript runtime environment

Step 4: Learn Express.js, a framework built upon Node.js to simplify the process of creating web application and API building

Step 5: Learn MongoDB, a NoSQL database to store and retrieve data from database.

Getting Started with MERN Stack:

There are two requirements to start a MERN stack project:

Step 1: Install node on your system depending on your Operating System:

Step 2: You need a code editor to work with so install a code editor, preferably we will use VS Code

Setting Up a MERN Stack Project

To setup MERN stack we need to create a folder structure for both frontend and backend. Then we have to define database schema to store and retrieve data from the database.

Follow the below steps to create a basic structure

Step 1: After the code editor is installed, create a new project folder. Then go to the project folder in command prompt/terminal and type below commands to create folder for frontend and backend 

mkdir frontend
mkdir backend

Step 2: Navigate to the frontend folder using the command

cd frontend

Step 3: Initialize a React Project using the command

npx create-react-app

Step 4: Now navigate to the backend folder using the command

cd..
cd backend

Step 5: Initialize the project backend using the command

npm init -y

Step 6: Install Express and other backend dependencies using the command

npm i mongodb express cors dotenv 

After following all the above steps a basic structure for MERN Stack application is created.

Getting to know MERN Stack components:  

1. MongoDB: Cross-platform Document-Oriented Database 

MongoDB is a NoSQL database where each record is a document comprising of key-value pairs that are similar to JSON (JavaScript Object Notation) objects. MongoDB is flexible and allows its users to create schema, databases, tables, etc. Documents that are identifiable by a primary key make up the basic unit of MongoDB. Once MongoDB is installed, users can make use of Mongo shell as well. Mongo shell provides a JavaScript interface through which the users can interact and carry out operations (eg: querying, updating records, deleting records).

Why use MongoDB? 

  • Fast – Being a document-oriented database, easy to index documents. Therefore a faster response.
  • Scalability – Large data can be handled by dividing it into several machines.
  • Use of JavaScript – MongoDB uses JavaScript which is the biggest advantage.
  • Schema Less – Any type of data in a separate document.
  • Data stored in the form of JSON –
    1. Objects, Object Members, Arrays, Values, and Strings
    2. JSON syntax is very easy to use.
    3. JSON has a wide range of browser compatibility.
    4. Sharing Data: Data of any size and type(video, audio) can be shared easily.
  • Simple Environment Setup – Its really simple to set up MongoDB.
  • Flexible Document Model – MongoDB supports document-model(tables, schemas, columns & SQL) which is faster and easier.
  • Creating a database: Simply done using a “use” command:
use database_name;
  • Creating a table: If the collection/table doesn’t exist then a new collection/table will be created:
db.createCollection("collection_name");
  • Inserting records into the collection:
db.collection_name.insert
(
{
"id" : 1,
"Name" : "Klaus",
"Department": "Technical",
"Organization": "Geeks For Geeks"
}
);
  • Querying a document:
db.collection_name.find({Name : "Klaus"}).forEach(printjson);

2. Express: Back-End Framework: 

Express is a Node.js framework. Rather than writing the code using Node.js and creating loads of Node modules, Express makes it simpler and easier to write the back-end code. Express helps in designing great web applications and APIs. Express supports many middlewares which makes the code shorter and easier to write.

Why use Express? 

  • Asynchronous and Single-threaded.
  • Efficient, fast & scalable
  • Has the biggest community for Node.js
  • Express promotes code reusability with its built-in router.
  • Robust API
  • Create a new folder to start your express project and type below command in the command prompt to initialize a package.json file. Accept the default settings and continue.
npm init
  • Then install express by typing the below command and hit enter. Now finally create a file inside the directory named index.js.
npm install express --save

  • Now type in the following in index.js to create a sample server.

JavaScript




const express=require('express'),
http=require('http');
const hostname='localhost';
const port=8080;
const app=express();
  
app.use((req, res)=> {
        console.log(req.headers); 
        res.statusCode=200; 
        res.setHeader('Content-Type', 'text/html'); 
        res.end('<html><body><h1>This is a test server</h1></body></html>');
});
const sample_server=http.createServer(app);
  
sample_server.listen(port, hostname, ()=> {
        console.log(`Server running at http: //${hostname}:${port}/`);});


  • Update the “scripts” section in package.json file

  • Then to start the server by running the below command
npm start

  • Now you can open the browser and get the output of the running server.

3. React: Front-End Library

React is a JavaScript library that is used for building user interfaces. React is used for the development of single-page applications and mobile applications because of its ability to handle rapidly changing data. React allows users to code in JavaScript and create UI components. 

Why use React? 

  • Virtual DOM – A virtual DOM object is a representation of a DOM object. Virtual DOM is actually a copy of the original DOM. Any modification in the web application causes the entire UI to re-render the virtual DOM. Then the difference between the original DOM and this virtual DOM is compared and the changes are made accordingly to the original DOM.
  • JSX – Stands for JavaScript XML. It is an HTML/XML JavaScript Extension which is used in React. Makes it easier and simpler to write React components.
  • Components – ReactJS supports Components. Components are the building blocks of UI wherein each component has a logic and contributes to the overall UI. These components also promote code reusability and make the overall web application easier to understand.
  • High Performance – Features like Virtual DOM, JSX and Components makes it much faster than the rest of the frameworks out there.
  • Developing Android/Ios Apps – With React Native you can easily code Android-based or IOS-Based apps with just the knowledge of JavaScript and ReactJS.
  • You can start your react application by first installing “create-react-app” using npm or yarn.
npm install create-react-app --global

OR 

yarn global add create-react-app
  • After that you can create a new react app by using.
create-react-app app_name
  • Then navigate into the “app_name” folder and type yarn start or npm start to start your application.

  • A typical React application looks like this:

  • Update index.js file

Javascript




ReactDOM.render(
    <h1>Hello DEVELOPERS!!</h1>,
    document.getElementById('root')
);


  • Use the below commands to run your application.
npm start

or 
 

yarn start

4. Node.js: JS Runtime Environment 

Node.js provides a JavaScript Environment which allows the user to run their code on the server (outside the browser). Node pack manager i.e. npm allows the user to choose from thousands of free packages (node modules) to download. 

Why use Node.JS? 

  • Open-source JavaScript Runtime Environment
  • Single threading – Follows a single-threaded model.
  • Data Streaming
  • Fast – Built on Google Chrome’s JavaScript Engine, Node.js has a fast code execution.
  • Highly Scalable
  • Initialize a Node.js application by typing running the below command in the command window. Accept the standard settings.
npm init
  • Create a file named index.js. 

Example: A basic Node.js example to compute the perimeter & area of a rectangle.

JavaScript




let rectangle= {
    perimeter: (x, y)=> (2*(x+y)), area: (x, y)=> (x*y)
};
  
function Rectangle(l, b) {
    console.log("A rectangle with l = "
        l + " and b = " + b);
  
    if (l <=0 || b <=0) {
        console.log("Error! Rectangle's length & "
        + "breadth should be greater than 0: l = " 
        + l + ", and b = " + b);
    }
  
    else {
        console.log("Area of the rectangle: " 
            + rectangle.area(l, b));
        console.log("Perimeter of the rectangle: " 
            + rectangle.perimeter(l, b));
    }
}
  
Rectangle(1, 8);
Rectangle(3, 12);
Rectangle(-6, 3);


  • Run the node application by running the below command in the command window.
npm start



Similar Reads

Difference between MEAN Stack and MERN Stack
Web development is a procedure or process for developing a website. A website basically contains three ends: the client side, the server side, and the database. These three are different sides of an application that combine together to deliver an application; all ends are implemented separately with different technologies. MEAN and MERN are the tec
3 min read
MERN Stack vs Java Full Stack
A website is a collection of various web pages made by the most popular technologies, like HTML, CSS, and JavaScript, along with other front-end and back-end technologies. A website contains primarily three sides: a client side, a server side, and a database. When it comes to the three sides of a website complete together, it is called a stack. In
6 min read
Difference between PERN and MERN stack
What is a stack, if you are familiar with full-stack development you might have come across the terms MEAN, MERN, MEVN, etc. These are web stacks consisting of a collection of software and frameworks used for building a web application from the front-end and back-end. You can learn any of these stacks to become a Full-stack developer. A stack usual
3 min read
How to Become a MERN Stack Developer?
Do you also get amazed at those beautiful websites that appear in front of you? Those are designed by none other than Full-Stack Developers Or MERN stack developers. They are software developers who specialize in building web applications using the MERN stack, which is a popular set of technologies for creating full-stack web applications. Also, fu
6 min read
Community Forum Page using MERN Stack
In the ever-expanding digital landscape, fostering meaningful connections within communities is paramount. The Community Forum Page project, developed using the MERN (MongoDB, Express, React, Node) stack, aims to provide a dynamic platform for users to engage in discussions, share valuable information, and cultivate a thriving community environment
8 min read
Restaurant App using MERN Stack
Creating a Restaurant app will cover a lot of features of the MERN stack. In this tutorial, we'll guide you through the process of creating a restaurant application using the MERN stack. The application will allow users to browse through a list of restaurants, view their menus, and add items to a shopping cart. Preview of final output: Let us have
11 min read
Chat Website using MERN Stack
The "Chat Website" project is a dynamic web application that is used for real-time communication. The MERN stack, comprised of MongoDB, Express.js, React.js, and Node.js, is a powerful combination of technologies for developing robust and scalable web applications. In this article, we'll explore the process of building a real-time chat website usin
4 min read
Bookstore Ecommerce App using MERN Stack
Bookstore E-commerce project is a great way to showcase your understanding of full-stack development. In this article, we'll walk through the step-by-step process of creating a Bookstore E-commerce using the MERN (MongoDB, Express.js, React, Node.js) stack. This project will showcase how to set up a full-stack web application where users can view,
8 min read
Social Media Platform using MERN Stack
In web development, creating a "Social Media Website" will showcase and utilising the power of MERN stack – MongoDB, Express, React, and Node. This application will provide users the functionality to add a post, like the post and able to comment on it. Preview Image: Let us have a look at how the final output will look like. Prerequisites:NodeMongo
8 min read
Summarizer Website using MERN Stack
The MERN stack, comprising MongoDB, Express, React, and Node is a powerful combination for building full-stack web applications. In this article, we'll see how we can create a Summarizer Website using MERN stack. Project Preview: Let us have a look at how the final output will look like. [caption width="800"]Project Preview[/caption]Pre-requisites:
4 min read
Article Tags :