The Wayback Machine - https://web.archive.org/web/20240916002555/https://www.geeksforgeeks.org/mern-stack/
Open In App

MERN Stack

Last Updated : 13 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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
Blackjack Game using MERN Stack
In this tutorial, we'll embark on a journey to create a fully functional Blackjack game using React for the frontend and Node for the backend. This engaging and interactive project will allow you to explore the realms of web development while learning how to implement key features of a classic card game. Preview of Final Output: Let’s have a look a
8 min read
Task Manager App using MERN Stack
Task Manager is very crucial to manage your tasks. In this article, we are going to develop a task manager application using the MERN stack. This application helps users to manage their tasks efficiently, offering essential features like creating new tasks, editing existing ones, and deleting tasks as needed. We'll walk through the step-by-step pro
10 min read
5 Essential Tools Every MERN Stack Developer Should use
To increase productivity, efficiency, and development experience, it is very important to have the right set of tools. In this post, we will explore the 5 most important essential tools that everyone should use if you are a MERN developer. In full-stack web development, the MERN stack is one of the most popular due to its flexibility, scalability,
3 min read
MERN Stack Development Roadmap for 2024
Curious about building modern web apps? Ever heard of the MERN stack? In this guide, I'll walk you through the steps to master it. Don't worry if you're new—I'll make it simple. By the end, you'll understand MERN, its tools, and where to learn more. Plus, I'll share cool project ideas for your portfolio. Ready to fall in? Let's get started! Let's s
15 min read
Crafting a stunning CRUD Application with MERN stack
Creating a CRUD (Create, Read, Update, Delete) application using the MERN stack is an excellent way to build dynamic web applications with JavaScript technologies. The MERN stack consists of MongoDB, Express.js, React, and Node.js, offering a full-stack JavaScript solution for building modern web applications. In this article, we will get through t
5 min read
5 Simple Steps for Authentication and Authorization in MERN Stack
Implementing authentication and authorization in a MERN stack application is crucial for ensuring the security of your application and protecting sensitive data. Here's an elaboration on the five simple steps you can take to achieve this: Table of Content Implementing Authentication and Authorization in MERN App:How Authentication is done in MERN S
8 min read
Text Translation Tool using MERN Stack
In this article, we’ll walk through the step-by-step process of creating a text translation application with MongoDB, React, ExpressJS, and NodeJS. This application will provide users with a user-friendly interface for translating text between different languages. Output Preview: Let us have a look at how the final output will look like. Prerequisi
7 min read
Project Idea | Build an AR based music learning platform using the MERN Stack
In this article, we will be building an AR-based web app called GuitAR. It teaches users to learn guitar by projecting the strings that are to be plucked on the guitar in the user's camera feed. Now, all the user has to do is to pluck the highlighted strings to play a particular song. Here is an sample image for better understanding. We will be bui
15+ min read
Social Fitness App using MERN Stack
Creating a Social Fitness App is a great opportunity for anyone who wants to understand full-stack development. In this article, we'll make a Social Fitness App from scratch using the MERN(MongoDB, Express.js, React, Node.js) stack. This project will help navigate backend development, and teach you the process of integrating frontend functionality
9 min read
Travel Journal App with MERN Stack with API
In this article, we are going to explore the project which is a travel journalling app, where users can log in and register, make journal entries describing the various places they traveled to, and also upload their images. They can search through the various entries they've made and also delete them. The website enables authentication and authoriz
15+ min read
MERN Stack Fundamentals: Data Persistence with MongoDB
The MERN Stack, comprising MongoDB, Express, React, and NodeJS, is a leading JavaScript platform for modern full-stack web apps. MongoDB offers a flexible NoSQL database, while Express provides a robust web framework. React enables dynamic user interfaces, and NodeJS facilitates server-side development. Together, they form a scalable, cohesive plat
11 min read
What to learn after MERN Stack?
Congratulations on mastering the MERN (MongoDB, Express.js, React, Node.js) stack! You've built dynamic and robust web applications, but the world of full-stack development is vast and ever-evolving. Wondering what's next on your learning journey? Let's explore the avenues you can take to broaden your skill set. Table of Content 1. GraphQL: Enhanci
4 min read
Expense Management System using MERN Stack
In this article, we’ll walk through the step-by-step process of creating a Expense Management System using the MERN (MongoDB, ExpressJS, React, NodeJS) stack. This project will showcase how to set up a full-stack web application where users can add their budget and put daily expenses that get deducted from the budget. Output Preview: Let us have a
14 min read
Ticket Raising Platform using MERN Stack
The Ticket Raising Platform project is a web application that enables users to create, manage, and track tickets for various issues or tasks. Built using the MERN (MongoDB, ExpressJS, ReactJS, NodeJS) stack, this project provides a comprehensive solution for efficiently handling ticket requests and resolutions. Preview Image of Final Output: Prereq
8 min read
35+ MERN Stack Projects with Source Code [2024]
The MERN stack, comprising MongoDB, Express JS, React, and Node JS, is a powerful combination that enables developers to build full-stack web applications using JavaScript. MongoDB serves as the database, Express.js handles server-side logic, React manages the client-side interface, and Node.js facilitates backend operations. This article delves in
6 min read
Music Streaming Platform using MERN Stack
In this tutorial, we'll walk through the process of creating a music streaming platform using the MERN stack. This project will allow users to browse playlists, view songs within each playlist, search for specific songs, and play them. We'll cover the basics of setting up a MongoDB database, creating RESTful APIs with Node.js and Express, and build
7 min read
Freelancer Portfolio Builder Application using MERN Stack
In today's digital age, having a professional portfolio is essential for freelancers to showcase their skills and attract potential clients. In this article, we'll dive into the process of building a Freelancer Portfolio Builder using the MERN (MongoDB, Express.js, React.js, Node.js) stack. This project will allow freelancers to create, edit, and m
5 min read
Beginner's Guide to User Authentication in MERN Stack
User authentication is an essential aspect of web development, allowing users to securely register, log in, and access protected resources within an application. This article aims to provide a beginner-friendly guide to implementing user authentication in a MERN (MongoDB, Express.js, React.js, Node.js) stack. Prerequisites:Node.jsMongoDBReact.jsExp
6 min read
What is MERN Stack ?
In web development, the MERN stack is one of the most popular, robust, and versatile technologies by which you can create dynamic and scalable web applications. Comprised of four key technologies – MongoDB, Express.js, React, and Node.js – the MERN stack offers a complete solution for full-stack web development. Table of Content What is the MERN St
4 min read
Neighborhood Safety Rating App with MERN Stack
In this project, we developed a web application called the Neighborhood Safety Rating App using the MERN stack, which includes MongoDB, Express.js, React.js, and Node.js. The app allows users to view and manage safety ratings for different neighborhoods. Project Preview: Prerequisites:-HTML, CSS, JavaScriptReact.jsNode.jsExpress.jsMongoDBAxios for
6 min read
Mindfulness Meditation App with MERN Stack
In today's time, stress and anxiety have become common challenges for most of us. To promote mental well-being and mindfulness, we created a Mindfulness Meditation App using MERN. This app allows users to create, edit, and delete meditation sessions, helping them cultivate a sense of peace and calmness in their daily lives. Project Preview: Prerequ
7 min read
The Future of MERN Stack [Top Trends and Predictions]
Web development is a field that keeps changing and this calls for technologies that are adaptable, efficient, and well-supported. Developers who want to create JavaScript-focused modern and scalable web applications will definitely choose the MERN stack (MongoDB, Express.js, React.js, Node.js). Will this be changed in the future? This article discu
9 min read
Job Search Portal with MERN Stack
In this tutorial, we'll guide you through the process of creating a Job Search Portal using the MERN Stack - MongoDB for storing job and user data, Express.js for building web applications, React.js for creating user interfaces, and Node.js for server-side programming. Output Preview: Prerequisite Mongo DBExpress JsReact JSNode JSApproachBegin by c
9 min read
Node.js Basics: Back-End Development in MERN Stack
Node.js is an open-source and cross-platform JavaScript runtime environment. It’s a powerful tool suitable for a wide range of projects. Node.js stands out as a game-changer. Imagine using the power of JavaScript not only in your browser but also on the server side. Table of Content What is MERN stack?What is Node?Why Node?Key features of NodeNode
7 min read
MERN Stack vs. Other Stacks: A Comparative Analysis
In web development, choosing the right technology stack is crucial for building efficient and scalable applications. Some popular choices are MERN stack( MongoDB, Express.js, React.js, and Node.js), LAMP Stack, MEAN Stack and Ruby on Rails. In this article, we will conduct a comparative analysis of the MERN stack with other stacks to understand the
8 min read
Music Discovery App with MERN Stack
In today's digital age, music discovery has become an integral part of our lives. With the rise of streaming platforms and personalized recommendations, users are constantly seeking new music experiences. In this article, we'll delve into the creation of a Music Discovery App using the MERN stack (MongoDB, Express.js, React.js, Node.js). This compr
8 min read
Day 1 of MERN-Stack Journey: Unveiling React.js Basics for Beginners
After completing vanilla JavaScript with Node.js, we are now moving into exploring other parts of the MERN stack from a beginner’s level. In this phase, we started with React.js. This session will span over 90+ days. On day 1, I explored the simple basics of React.js and understood its abilities, features, and advantages. What is React?React is a h
5 min read
Article Tags :