The Ultimate Guide to MERN Stack

MERN STACK

The MERN Stack is a web development tech stack consisting of MongoDB, Expres.js, React.js and Node.js enabling you to build feature rich single page web applications using a single programming language, JavaScript.

What is the MERN Stack?

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

I’m beginning with the 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 an example of data stored in MongoDB looks like:

{
_id: ObjectId("5fdf7cd797334f00175e956c")
name: "Darshan mandade"
email: "mandadedarshan@gmail.com"
password: "itsasecret!"
createdAt: 2020-12-20T16:33:27.667+00:00
updatedAt: 2021-01-01T08:06:15.269+00:00
__v: 0
}

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

| id |    name    |            email            |  password   |
| 1 | Darshan | mandadedarshan@gmail.com | itsasecret! |

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

  • 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!

Alrightm 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 Atlast 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 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

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'))

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.

  • 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

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.

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 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:

If you’re interested in knowing more about the internal working of NodeJS, such as event loop and more.

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

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 and master it. Let us now talk about some things we are yet to cover, such as authentication, authorization, and state managment.

Authentication

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

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

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?

New to Web Development:

My recommended learning path would be:

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:

Let’s Look at the Alternatives

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

If you want to learn more about MERN Stack checkout Sonny’s YouTube channel for more amazing content here.

Share this article with anybody you think would benefit from this. If you have any suggestions, feel free to hit me up. I hope you enjoyed this article. If you did, make sure to let me know in the comments down below and don’t hesitate to buy me a coffee by clicking below👇!

https://www.buymeacoffee.com/papareact
https://www.buymeacoffee.com/papareact

Thank You!

Darshan Mandade
(PAPA Team Writer)

Python Fullstack Developer | Blogger | Web Developer | Mentor. Let's Connect on IG: @Darshu.codes