DEV Community

Cover image for The Ultimate Guide to MERN Stack
Nitin Ranganath
Nitin Ranganath

Posted on • Originally published at thesmartcoder.dev

The Ultimate Guide to MERN Stack

The Modern Web

Websites have come a long way from what they used to be a decade ago. We started with plain HTML and CSS websites. Then came JavaScript and revolutionized the way the web works. From that point onward, web technologies have made significant strides, owing to JavaScript frameworks, which made single-page applications or SPAs a thing. Today, we're able to build websites that fetch the code files from the server once and never reload again, even while visiting other pages. How does this work?

If you've ever wanted to become a full-stack web developer, the chances are that you came across the term MERN Stack. Worry not if you haven't, though.

  • What is it?
  • what does it stand for
  • How can you become a MERN stack developer?

I'm here to demystify it and introduce you to one of the trendiest web development tech stacks while providing you a proper roadmap as well as resources alongside. Are you excited? Let's dive right into it and begin with understanding the core concepts.

Table of Contents


What is the MERN Stack

The MERN stack is a web development tech stack consisting of MongoDB, ExpressJS, ReactJS NodeJS and enables you to build feature-rich single page web applications using a single programming language, JavaScript. Some developers consider this to one of the key reasons why the MERN stack is so popular. You can use your proficiency in a single language to manage both the front and back of your web application.

Now that we have a basic understanding of the MERN stack let's dive deeper into the technologies it consists of, starting with MongoDB.


MongoDB

MongoDB Banner

MongoDB is a NoSQL database in which data is stored in documents that comprise key-value pairs, sharing a lot of resemblance to JSON or JavaScript Object Notation. Woah, Woah, too much jargon? Don't worry! Let's break the above sentence into smaller chunks.

I am beginning with SQL vs. NoSQL. In SQL databases, data is stored in tables. Tables are just a collection of data in tabular form through rows and columns. Time for some visual representation!

Here's how the data stored in MongoDB looks like:

{
    _id: ObjectId("5fdf7cd797334f00175e956c")
    name: "Nitin Ranganath"
    email: "nitinranganath@gmail.com"
    password: "itsasecret!"
    createdAt: 2020-12-20T16:33:27.667+00:00
    updatedAt: 2021-01-01T08:06:15.269+00:00
    __v: 0
}
Enter fullscreen mode Exit fullscreen mode

And here's out the data stored in MySQL, a SQL-based database looks like:

| id |    name    |            email            |  password   |
|  1 |    Nitin   |   nitinranganath@gmail.com  | itsasecret! |
Enter fullscreen mode Exit fullscreen mode

MongoDB is excellent in so many aspects, making it a terrific choice for your upcoming projects. Some of these are:

  • High performance through indexing
  • Dynamic schemas for models
  • High scalability through distributing data on multiple servers
  • Ability to store geospatial data through GeoJSON
  • Auto replication

And a lot more!

Alright, but how exactly shall we use MongoDB to store our data in a MERN stack web application? While we can use the mongodb npm package, it is more convenient to use an ODM or Object Data Modelling library such as mongoose.

If I were to prepare a checklist of stuff you learn regarding MongoDB for building full stack web applications, it would consist of:

  • Setting up local MongoDB or cloud MongoDB Atlas database
  • Creating models and schemas
  • Perform CRUD (Create, Read, Update & Delete) operations on the database

Bonus points for:

  • Linking two related models using refs
  • Understanding mongoose pre and post hooks
  • Mongoose data validation

ExpressJS

Express Banner

Moving on to ExpressJS, let's first try to understand what it exactly is, why do we use it, and do we need it (spoiler alert, it's not!). Express is the most popular web application framework which uses NodeJS. In MERN stack applications, Express's role is to manage our backend API server, the one from which we will be fetching data from a database via our React frontend.

Express is used to listen to a particular port of our server for requests from the user or frontend in simpler terms. We can create different routes for each endpoint which the user accesses. Here's an example to make it clear what I'm talking about:

GET https://ourwebsite.com/products     -> Fetches all products
GET https://ourwebsite.com/products/1   -> Fetches the product with ID of 1
Enter fullscreen mode Exit fullscreen mode

As the programmer, we design and build the routes to get the appropriate data from the right endpoint. That's what Express allows us to do quickly. Remember when I said Express is not precisely required? That's because we can use the core http module that NodeJS provides us to create the routes that I mentioned above. Then why don't we use that? Because Express makes the whole developer experience much better.

// Using http
const http = require('http');
http.createServer((req, res) => {
    if (req.url === '/products' && req.method === 'GET') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(products));
    }
}).listen(5000, console.log('Server running on port 5000'));

// Using express
const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.json(products);
})

app.listen(5000, console.log('Server running on port 5000'))
Enter fullscreen mode Exit fullscreen mode

This was just an example, quite a simple one too. Express code is much more cleaner to read as well as write. Now, coming to things that you should learn concerning Express, as a MERN stack developer:

  • Setting up an express server and listening on the desired port
  • Create routes/endpoints for data CRUD operations through GET, POST, PUT, and DELETE
  • Reading JSON form data sent from frontend via express.json() middleware
  • Setting up an ODM like mongoose with Express

Bonus point for:

  • Separating the logic in different files such as controllers, routes, and models
  • Creating custom middlewares to handle errors and more

ReactJS

ReactJS Banner

If you want to become a frontend or a full stack web developer, the chances are that you've heard about JavaScript frameworks such as React, Vue, or Angular. For now, let's focus on React: undeniably, the most popular JavaScript frontend library. We'll be having a brief look at Vue and Angular to discuss the MEVN and MEAN stack. But let's learn more about React for now.

As mentioned above, it is a library created by Facebook that allows us to develop dynamic and interactive user interfaces on our websites efficiently. It offers dynamic interfaces using props (short for properties) and state in our web application. Moreover, it provides us with the ability to break down our code into smaller chunks, known as components, which make them more versatile. Components can be imported and used in multiple places in our web application, saving us time and energy to avoid rewriting the code with minor changes and keep our codebase DRY (don't repeat yourself.

Components

One of the best things about React is that you can use it to create single-page applications or SPAs for short. What's unique about SPAs is that we only have to load all our static assets like HTML, CSS, and JavaScript only once compared to traditional websites that reload and fetch new assets every time you visit a new page of a website. For routing, react-router-dom is one of the most popular ways to do so. In a nutshell, load once and access the full website without ever reloading, unless you manually reload, duh!

We can have a whole separate article to discuss React and what makes it so great. Since this is more of an overview of the MERN stack and not just React, I'll list down some of the features of React which you'll be using while developing web applications, and you should definitely learn:

  • Creating appropriate components and using props
  • Write functional React code
  • Commonly used React hooks such as useState and useEffect
  • Managing props in a component through the useState hook
  • Conditional rendering
  • Making API calls from the useEffect hook to get data from the backend
  • Making form inputs controlled and handling form submits

Additionally, you sharpen your React skills with the following:

  • Managing global state through Context API or Redux
  • Learning the use cases of less common React hooks like useRef, useMemo, and more
  • Using styled-components or other CSS in JS methods

NodeJS

NodeJS Banner

Finally, we complete the overview of the technologies that make up the MERN stack by exploring NodeJS. First things first, what is NodeJS, and how is it different from JavaScript? Is it something different altogether; why do we use it in the first place; can't we use JavaScript instead? I'll try answering all these common questions in the upcoming paragraphs. But first, let's see what NodeJS is.

NodeJS is a cross-platform JavaScript runtime environment that uses Google's V8 engine to run JavaScript code outside the browser. JavaScript intends to run on browsers, but we don't have browsers on our backend, do we? This is where NodeJS shines. It enables us to write JavaScript, which can run on our backend servers. But how does it achieve this? It uses something known as the V8 engine and libuv, a whole other topic. Here's a visual representation of how the NodeJS architecture works in a nutshell:

NodeJS Architecture

If you're interested in knowing more about the internal working of NodeJS, such as event loop and more, here's an excellent video to get you started with.

Coming back to the MERN stack, the purpose of NodeJS is simple. Allow us to write our backend in JavaScript, saving us the trouble of learning a new programming language capable of running the backend. It's an event-driven, non-blocking I/O model moreover. While there's not much specific to NodeJS that you have to learn to build a MERN stack application, here are some related things you should take a look at:

  • Initialising a npm package
  • Installing npm packages through npm or yarn
  • Importing and exports modules using commonJS
  • Understanding the package.json file

Bonus points for:

  • Accessing the filesystem using inbuilt fs package
  • Setting up a server with an inbuilt http package (not required if using express)

Combining The Technologies & Exploring How It Works Together

How It Works Banner

In the previous section, we had a look at all the four technologies which constituted the MERN stack. While each one of them is fantastic to work with individually, combining these technologies working together like clockwork results in an excellent web application. That's what we're going to learn about in this section. Knowing each technology is half the skill, while the other half is to piece them together into something meaningful. What could be better than another visual representation of a MERN stack web application, where the user is interacting with the frontend, which in turn is accessing the backend and the database.

Block Diagram

Let's understand the whole mechanism by taking an example. Assume that we have built a great e-commerce web application that sells apparel. We have a customer who is currently visiting our website to shop for some sneakers. We have a link on the landing page that takes the user to the sneakers page. So how do we get the data from the backend? Let's take it one step at a time.

  1. User visits our website's landing page built using React.
  2. User clicks on the link to shop for sneakers. We render the sneakers page without reloading the page since we have built a single page application.
  3. We do not have the sneakers data at this point, i.e., the state is empty. Therefore, we make an API call to our backend to fetch the data.
  4. Since the process of fetching the data from our database is asynchronous, meaning that it will take some amount of time for it to finish executing, we show the user a loading GIF while sneakers data is being retrieved.
  5. In our backend, ExpressJS looks at the endpoint (route) we've hit and executed the appropriate controller function, which is used to retrieve sneakers data.
  6. Inside this controller function, we use mongoose to query our database and get the data and return it in the form of JSON (JavaScript Object Notation).
  7. This JSON data is sent back to our React frontend, where we can update the state with our newly fetched data.
  8. Since our state got updated, React will re-render the components which depend on it, and subsequently, we replace our loading GIF with the sneakers information.

And that's how all the technologies work together. Do not fret if you did not understand it entirely just yet. Since this mechanism is so commonly used, you will eventually understand and master it. Let us now talk about some things we are yet to cover, such as authentication, authorization, and state management.

Authentication

Most of the websites nowadays allow you to create a user account for yourself through sign-up and sign-in procedures. We want this functionality in our web application, don't we? Even the simplest of applications such as a to-do list can be made interesting if we can associate each to-do with the user who created it. So how do we authenticate a user?

While signing up to a website, we essentially create a user with email and password fields and store them into our database. But here's a catch. It is a bad practice to store the user passwords in plaintext or as it is due to security reasons. To overcome this, we can hash the user passwords using some strong hashing algorithm to secure them. I use the bcryptjs package from npm for this purpose.

Another option is to use OAuth, such as Google OAuth, to sign up the user to our website using his/her Google account. This saves us the hassle of manually taking care of all the security measures but adds complexity to the project due to handling API keys for OAuth with care.

Authorization

In the simplest terms, authorization is to restrict some routes to only specific types of users. For example, we do not want a user who's not logged in to place an order since we need to bind the user to each order. Similarly, we do not wish for any random user to delete someone else's account. Such functionality should be only restricted to admins. And that is why we need authorization.

We can restrict access to our backend API using some conditions to prevent misuse through authorization. One of the most popular ways to implement authorization is to use JSON Web Tokens, or JWT for short. Whenever a user registers or logs in, we send back a token to the user. With this token being passed into headers during future API calls, we can uniquely identify the user by encoding the user ID in the payload. This can help us check whether the user is logged in, is an admin, and determine which user is accessing the routes.

State Management

As your website grows, it is problematic to manage your global state. The user who is logged in can be an example of global state. Why? Because this information or state might be needed in multiple components, such as a navigation bar, profile card, and much more. Since we need to keep our shared state consistent across all the components which use it, having component level state with useState will not be feasible.

Another solution might be to store the state in the top-most component and pass it to other components that require it as props. Even this approach is not recommended as you might have to pass the state as props to multiple components and multiple levels, even to the components that do not require the state to pass the state from top-level component to bottom-level components.

This is why we can use Context API or Redux to maintain a global store of state from which we can access the state in all the components we require, without passing it as props. While some argue that Redux is not needed ever since Context API came out, I still find lots of codebases using it, and it might be a good idea to learn it.


How To Become a MERN Stack Developer?

Phew! That was a lot to take in. But the good thing is that you don't need to memorize any of it. Developers learn by doing, not memorizing! With that being said, you must be wondering how to become a MERN stack developer. That will be the prime focus of this section, where I'll be providing you with my own roadmap that you can take inspiration from and start your journey, whether you are new to web development or just exploring other tech stacks.

New to Web Development:

If you're new to web development or even programming in general, I would highly recommend giving yourself enough time and learning the basics first. This includes how the web works, HTML, CSS, and JavaScript at first. Once you're comfortable building static websites with them, you can either choose to learn a JavaScript framework like React or explore the backend path with NodeJS. The way you choose is up to you, but ultimately, you'll have to learn both of them. A fantastic way to sharpen your skills is by making javascript projects for beginners.

My recommended learning path would be:

Beginner Roadmap

So we start with the basics, understanding the web, and delving into the frontend world, and starting with HTML, CSS and JavaScript so that you can build some awesome static websites such as landing pages with responsive design. Using a version control system like Git is pretty crucial since you'll be using it quite a lot in the future. Guess what? You're already good enough to look for some freelance work.

Before writing some backend code, you should understand HTTP and the HTTP methods such as GET and POST. For the MERN stack, you'll use NodeJS in combination with ExpressJS to layout your backend. For interacting with your MongoDB database, you can use mongoose. Add a bit of authentication and authorization skills, and you're ready to build a full-stack web application.

Finally, we return to the frontend and get our hands on React, a framework (technically, a library) that will take your websites and developer experience to the next level. You can see yourself building social network web apps, e-commerce web apps, and virtually any web app you want with the help of whatever you've learned so far. Exciting!

Experienced Developers Switching Tech Stack:

While the roadmap remains the same for even experienced developers, you can skip the HTML, CSS, and JavaScript parts. You may already be familiar with it and focus on grasping a good understanding of NodeJS how it works. Due to your previous knowledge of a different tech stack, I'm confident that you'll be able to adapt NodeJS pretty soon. Making careful decisions on how to better architecture your web app, optimizing it, and writing clean code will definitely give you an advantage over others.


Resources & Tools

A quick note: You certainly do not watch each of these resources. Pick whatever you like the go with it. One of the mistakes that I made was that I kept switching between multiple resources due to the fear of missing out. Trust me, and you'll be fine. All of these resources are amazing and equally good. And you don't necessarily have to pick from just this list. A quick YouTube or Google search will also do.

Free Courses

FreeCodeCamp YouTube Channel

HTML, CSS and JavaScript:

HTML & CSS Playlist by Brad Traversy - Crash courses & tons of awesome projects.

12HR+ YouTube Coding Bootcamp 2021! by Ania Kubow - Learn HTML, CSS and JavaScript in a single video.

HTML & CSS Playlist by The Net Ninja - Byte sized videos to keep your interested.

Vanilla JavaScript Playlist by Brad Traversy - Solidify your JavaScript knowledge with lots of projects.

Modern JavaScript Playlist by The Net Ninja - Learn modern JavaScript including ES6

JavaScript for Beginners Course (2020) by Colt Steele - Get yourself started with JavaScript in a couple of hours.

NodeJS, ExpressJS & MongoDB:

NodeJS Playlist by Brad Traversy - Gem of a resource for all things NodeJS

NodeJS Crash Course by Dev Ed - Make learning NodeJS fun

Building a RESTful API with Express & MongoDB by Dev Ed - Learn to build a REST API

NodeJS Authentication with JWT by Dev Ed - Explore authentication and authorization

Introduction to MongoDB by Academind - Get yourself familiar with MongoDB

MongoDB + Mongoose + Node.js Crash Course by Codedamn - Teach yourself backend in an hour

React & Redux:

Modern React Playlist by The Net Ninja - Byte sized, up to date React tutorials

React Hooks Playlist by Web Dev Simplified - Learn all about React Hooks in a single playlist

React Crash Course 2020 by Codedamn - Understand React by building a big project

React Projects Playlist by Traversy Media - Build amazing React projects

Redux for Beginners for Dev Ed - Get to know about Redux in a fun way

Redux Explanation by Stephen Grider - One of the best explanations of Redux

Tools To Use

Visual Studio Code - Free, open source and one of the best text editors

Figma - The collaborative interface design tool

GitHub Desktop - Desktop client for GitHub

Google Lighthouse - Test your website's performance and SEO

React Developer Tools - Chrome extension for testing React websites

Redux DevTools - Chrome extension for testing Redux

JSON Viewer - Chrome extension for display JSON in a much more readable manner

WhatRuns - Check what tech stack your favorite website uses

Postman - Test your APIs

Design Resources

Design Resources for Developers - A repo full of tons of design resources

Coolors - Generate color schemes with ease

Grabient - Awesome gradient colors

Google Fonts - Fonts to use in your websites

FontAwesome - Collections of icon fonts


Let's Look at the Alternatives

There are many ways to achieve the same result when it comes to programming. Web development is no exception. Let's look at some popular alternatives to the MERN stack.

The MEVN Stack

The MEVN stack uses Vue instead of React in the frontend. VueJS is an open-source JavaScript framework with over 175k+ stars on GitHub and is undoubtedly a popular choice. It is considered to be easier to learn than React, but since it falls behind a bit when it comes to the number of jobs available for Vue developers comparatively. However, the framework itself is incredible and worth trying. It's also not backed by any corporations, unlike React and Angular.

The MEAN Stack

Talking of Angular, it is also a frontend framework that uses TypeScript instead of JavaScript to build web applications. It is arguably the hardest to learn compared to React and Vue but also used by lots of enterprises. It is developed by Google and focuses on high performance and MVC architecture.


Final Words

Being a developer is not easy. There are a lot of new advancements, frameworks, and technologies that keep coming out, and staying up to date is hard. Do not give in to the shiny object syndrome and believe in the process. Allow yourself to take time and make mistakes. We all learn from that. I hope this guide helped you to get started with the MERN stack. Good luck ahead!

Top comments (33)

Collapse
 
almasali profile image
Md. Almas Ali

Awesome! Very useful for beginners.

Collapse
 
itsnitinr profile image
Nitin Ranganath

Thank you! Glad it was helpful.

Collapse
 
dailydevtips1 profile image
Chris Bongers

Wow, what a huge resource list!
Well done Nitin! 👋

Collapse
 
itsnitinr profile image
Nitin Ranganath

Thanks Chris! Credits to all the amazing content creators and developers who made these resources possible.

Collapse
 
prgbono profile image
Paco Ríos

Well done Nitin, really good post.
Not only the part of MERN specifics, also the later reading from 'How To Become a MERN Stack Developer?' is very interesting in my opinion!

Collapse
 
itsnitinr profile image
Nitin Ranganath

Thank you so much! I genuinely appreciate your comment.

Collapse
 
nadeeminamdar profile image
nadeeminamdar

Hey Nitin, you did an awesome job writing this. Kudos!

Collapse
 
itsnitinr profile image
Nitin Ranganath

Thank you so much!

Collapse
 
h3li0 profile image
Helio da Silva Jr.

Fantastic post ! Thank you.

Collapse
 
itsnitinr profile image
Nitin Ranganath

Thanks for reading :)

Collapse
 
collinsjumah profile image
Collins Jumah

Awesome guide and resources. Big thanks

Collapse
 
itsnitinr profile image
Nitin Ranganath

You're very welcome!

Collapse
 
sateeshv1 profile image
sateesh velmala

very descriptive and professional way of explaining and guiding awesome job

Collapse
 
itsnitinr profile image
Nitin Ranganath

Thanks a lot! Really appreciate it.

Collapse
 
bhavesh392 profile image
Bhavesh⚡

Nitin bhai, ye article nahi h - ye gold mine h.
Thanks for it

Collapse
 
itsnitinr profile image
Nitin Ranganath

Hahaha, thank you so much Bhavesh bhai!

Collapse
 
hb profile image
Henry Boisdequin

Great post!

Collapse
 
itsnitinr profile image
Nitin Ranganath

Thank you, Henry!

Collapse
 
gauravrandheer profile image
Gaurav

Awesome!!!

Collapse
 
itsnitinr profile image
Nitin Ranganath

Thanks for reading :)

Collapse
 
simonholdorf profile image
Simon Holdorf

What a fantastic read, Nitin, thank you very much! So many useful tips and resources!

Collapse
 
itsnitinr profile image
Nitin Ranganath

Thanks for reading! Really glad you found value in it.

Collapse
 
programador51 profile image
programador51

Thanks, this is a perfect guide for the modern web development.

Collapse
 
andrewbaisden profile image
Andrew Baisden

Amazing this guide really is ultimate good work!

Collapse
 
itsnitinr profile image
Nitin Ranganath

Thank you so much for reading.

Collapse
 
mcwachira profile image
mcwachira

The guide and resources are really good .Thanks

Collapse
 
itsnitinr profile image
Nitin Ranganath

You're welcome!

Collapse
 
yitzhakbloy profile image
yitzhak-bloy

Great article!
Thanks

Collapse
 
itsnitinr profile image
Nitin Ranganath

Pleasure's mine! Thanks for reading.