CodeNewbie Community 🌱

Cover image for Beginner's Guide to the MERN Stack (Roadmap & Resources)
Nitin Ranganath
Nitin Ranganath

Posted on • Originally published at thesmartcoder.dev

Beginner's Guide to the MERN Stack (Roadmap & Resources)

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 in JavaScript and revolutionised the way the web works. From that point onward, web technologies have made major strides, owing to JavaScript frameworks which made single page applications or SPAs a thing. Today, we're able to build websites that fetches the code files from 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, 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. Excited? Let's dive right into it and begin with understanding the core concepts.

Introduction to MERN Stack

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

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

MongoDB

MongoDB Banner

MongoDB is a NoSQL database in which data is stored in the form of documents which comprises of 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.

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 great in so many aspects, which makes it an awesome 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 actually need it (spoiler alert, it's not!). Express is the most popular web application framework which uses NodeJS. In MERN stack applications, the role of Express is to manage our backend API server, the one from which we will be fetching data from database via our React frontend.

In simpler terms, Express is used to listen to a particular port of our server for requests from the user or frontend. 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

We, as the programmer, design and build the routes in order to get the appropriate data from the appropriate endpoint. That's what Express allows us to do easily. Remember when I said Express is not exactly 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 just 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 with respect to 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, 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 on Vue and Angular as well, to discuss about the MEVN and MEAN stack. But let's learn more about React for now.

As mentioned above, it is a library created by Facebook which allows us to develop dynamic and interactive user interfaces on our websites in an efficient way. It offers dynamic interfaces using props (short for properties) and state in our web application. Moreover, it offers us the ability to break down our code into smaller chunks, known as components which make them more versatile. Components can 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 special about SPAs is that we only have to load all our static assets like HTML, CSS and JavaScript only once as compared to traditional websites which 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 just to discuss about React and what makes it so great. Since, this is more of an overview to the MERN stack and not just React, I'll just 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 backend
  • Making form inputs controlled and handling form submits

Additionally, you can step up your React game 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 Banner

Finally, we complete overview of the technologies that make up 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 the 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 which uses Google's V8 engine to run JavaScript code outside the browser. JavaScript is intended 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 V8 engine and libuv, a whole other topic altogether. 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 awesome 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 itself, saving us the trouble of learning a new programming language which is 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 in order to build 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 server with 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 look at all the 4 technologies which constituted the MERN stack. While each one of them is amazing to work with individually, the combination of these technologies working together like a clockwork results into an amazing web application. That's what we're going to learn about in this section. Knowing the each individual 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 build an amazing e-commerce web application which sells apparels. We have a customer who is currently visiting our website to shop for some sneakers. On the landing page, we have a link which takes the user to the sneakers page. So how do we get the data from 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 of time 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 executes 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 completely just yet. Since this mechanism is so commonly used, you will eventually understand and master it. Let us now talk about some things which we are yet to cover such as authentication, authorization and state management.

Authentication

Most of the websites nowadays allow you to create an user account for yourself through signup and signin procedures. We definitely 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, what we essentially do is create a user with email and password fields and store them into our database. But here's a catch. It is a bad practise 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 make it safe and secure. 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 measure but adds a bit of complexity to the project due to handling API keys for OAuth with care.

Authorization

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

Through authorization, we can restrict the access to our backend API using some conditions in order to prevent misuse. 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 to check whether the user is logged in, is admin and to identify which user is accessing the routes.

State Management

As your website grows, it gets a bit 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 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 store the state in the top-most component and pass it other components which 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 which do not require the state just in order to pass the state from top-level component to bottom-level components.

This is why we can use Context API or Redux in order 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 really 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, wasn't it? But the good thing is that you don't need to memorise any of it. Developers learn by doing, not memorising! With that being said, you must be wondering how to become a MERN stack developer. And that is going to be the prime focus of this section, where I'll be providing you with my own roadmap which you can take inspiration from and start your journey, whether you are new to web development or just exploring other tech stack.

New to Web Development:

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

My recommended learning path would be:

Beginner Roadmap

So we start with the basics, understanding the web and delving into the frontend world. Starting off 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 important 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 have a good understanding of HTTP and the HTTP methods such as GET and POST. For the MERN stack, you'll be using NodeJS in combination with ExpressJS to lay out 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 back to the frontend and get our hands on React, a framework (technically, a library) which will take your websites and developer experience 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 learnt so far. Exciting!

Experienced Developers Switching Tech Stack:

While the roadmap remains the same for even experienced developers, you can skip through the HTML, CSS and JavaScript part as you may already be familiar with it and focus on grasping a good understanding of NodeJS and how it works. Due to your previous knowledge of a different tech stack, I'm confident that you'll be able to adopt NodeJS pretty soon. Making careful decisions on how to architecture your web app better, 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, you'll be fine. All of these resources are amazing and equally good. And you don't have necessarily 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 favourite 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

When it comes to programming, there are lots of ways to achieve the same result. 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 which has over 175k+ stars on GitHub and certainly is a popular choice. It is considered to be easier to learn than React but since it falls behind a bit when it comes the amount of jobs available for Vue developers comparatively. However, the framework itself is awesome 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 which uses TypeScript instead of JavaScript to build web applications. It is arguably the hardest to learn among React, Vue and Angular but also used by lots of enterprises. It was developed by Google and focuses on high performance and MVC architecture.

Final Words

Being a developer is not easy. There's a lot of new advancements, frameworks and technologies that keep coming out and staying up to date is hard. Do not give into 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 (4)

Collapse
 
sujitmohanty profile image
Sujit Mohanty

Such an amazing write-up! Thank You Nitin

Collapse
 
itsnitinr profile image
Nitin Ranganath

Thank you so much! I'm really glad you liked it.

Collapse
 
ayden2874 profile image
Ayden Peter

Writing can be amazing. There are many different ways to write, and there are many different types of writing that can be amazing. The engineering resume writer share some of the tips that can help you out.

Collapse
 
sofiiasov profile image
SofiiaSov

Great post about web development technology stack, thanks!