The MERN Stack Complete Guide.

Muhammad Suheer
19 min readSep 2, 2021

--

MERN Stack

Note: In this bIog i also list the top MERN Stack courses on Udemy with the Download link means you can get the paid top courses without paying.

What Is MERN?

Any web application is made by using multiple technologies. The combination of these technologies is called a “stack,” popularized by the LAMP stack, which is an acronym for Linux, Apache, MySQL, and PHP, which are all open-source components. As web development matured and interactivity came to the front. single page applications (SPAs) became more popular. An SPA is a web application prototype that avoids refreshing a web page to display new content; it instead uses lightweight calls to the server to get some data or snippets and updates the web page. The result looks quite useul when compared to the old way of reloading the page entirely. This brought about a rise in front-end frameworks, since much of the work was done on the client side. At approximately the same time, although completely unrelated, NoSQL databases also started gaining popularity. React is remarkably flexible. Once you have learned it, you can use it on a vast variety of platforms to build quality user interfaces. React is a library, NOT a framework. Its library approach has allowed React to evolve into such a remarkable tool. Node.js, a server-side JavaScript runtime environment, and Express, a web server built on Node.js, formed the middle tier, or the web server. This stack is arguably the most popular stack for any new web application these days. React

What are MERN Components?

I’ll give a quick introduction to the main components that form the MERN stack and a few other libraries and tools that you’ll be using to build your web application.

MERN stands for MongoDB, Express, React, Node, after the four key technologies that make up the stack.

  • MongoDB — document database
  • Express(.js) — Node.js web framework
  • React(.js) — a client-side JavaScript framework
  • Node(.js) — the premier JavaScript web server

1- React

React anchors the MERN stack. In some sense, it is the defining component of the MERN stack. React is an open-source JavaScript library maintained by Facebook that can be used for creating views rendered in HTML. Unlike AngularJS, React is not a framework. It is a library. Thus, it does not, by itself, dictate a framework pattern such as the MVC pattern. You use React to render a view (the V in MVC), but how to tie the rest of the application together is completely up to you.

I found some interesting facts about React that makes it stand out

Why Facebook Invented React?

The Facebook folks built React for their own use, and later they open-sourced it. Why did they have to build a new library when there are tons of them out there? React was born not in the Facebook application that we all see, but rather in Facebook’s Ads organization. Originally, they used a typical client-side MVC model, which had all of the regular two-way data binding and templates. Views would listen to changes on models, and they would respond to those changes by updating themselves. Soon, this got pretty hairy as the application became more and more complex. What would happen was that a change would cause an update, which would cause another update (because something changed due to that update), which would cause yet another, and so on. Such cascading updates became difficult to maintain because there were ingenious difference in the code to update the view, depending on the root cause of the update. Then they thought, why do we need to deal with all this, when all the code to depict the model in a view is already there? Aren’t we replicating the code by adding smaller and smaller snippets to manage chnages? Why can’t we use the templates (that is, the views) themselves to manage state changes? That’s when they started thinking of building something declarative rather than imperative.

Declarative:

React views are declarative. What this really means is that you, as a programmer, don’t have to worry about managing the effect of changes in the view’s state or the data. In other words, you don’t worry about changes or mutations in the DOM caused by changes to the view’s state. How does this work? A React component declares how the view looks like, given the data. When the data changes, if you are used to the jQuery way of doing things, you’d typically do some DOM manipulation. Not in React. You just don’t do anything! The React library figures out how the new view looks, and just applies the changes between the old view and the new view. This makes the views consistent, predictable, easier to maintain, and simpler to understand. Won’t this be too slow? Won’t it cause the entire screen to be refreshed on every data change? Well, React takes care of this using its virtual DOM technology. You declare how the view looks, not in the form of HTML or a DOM, but in the form of a virtual representation, an in-memory data structure. React can compute the differences in the virtual DOM very efficiently, and can apply only these changes to the actual DOM. Compared to manual updates which do only the required DOM changes, this adds very little overhead because the algorithm to compute the differences in the virtual DOM has been optimized to the hilt.

Component-Based:

The fundamental building block of React is a component, which maintains its own state and renders itself. In React, all you do is build components. Then, you put components together to make another component that changes a complete view or page. A component encapsulates the state of data and the view, or how it is rendered. This makes writing and reasoning about the entire application easier, by splitting it into components and focusing on one thing at a time. Components talk to each other by sharing state information in the form of read-only properties to their child components and by callbacks to their parent components.

No Templates:

Many web application frameworks rely on templates to automate the task of creating repetitive HTML or DOM elements. The templating language in these frameworks is something that the developer will have to learn and practice. Not in React. React uses a full-featured programming language to construct repetitive or conditional DOM elements. That language is none other than JavaScript. For example, when you want to construct a table, you write a for(…) loop in JavaScript, or use the map() function of an Array. There is an intermediate language to represent a virtual DOM, and that is JSX, which is very similar to HTML. It lets you create nested DOM elements in a familiar language rather than hand-construct them using JavaScript functions. Note that JSX is not a programming language; it is a representational markup like HTML. It’s also very similar to HTML If you have to learn then you can Read(https://reactjs.org/docs/jsx-in-depth.html). You don’t have to use JSX; you can write pure JavaScript to create your virtual DOM if you prefer. But if you are used to HTML, it’s simpler to just use JSX. Don’t worry about it; it’s really not a new language that you’ll need to learn

Isomorphic:

React can be run on the server too. That’s what isomorphic means: the same code can run on both server and the browser. This allows you to create pages on the server when required, for example, for SEO purposes. The same code can be shared on the server to achieve this. On the server, you’ll need something that can run JavaScript, and this is where I introduce Node.js.

2- Node.js

Simply put, Node.js is JavaScript outside of a browser. The creators of Node.js just took Chrome’s V8 JavaScript engine and made it run independently as a JavaScript runtime. If you are familiar with the Java runtime that runs Java programs, you can easily relate to the JavaScript runtime: the Node.js runtime runs JavaScript programs.

Node.js Modules

In a browser, you can load multiple JavaScript files, but you need an HTML page to do all that. You cannot refer to another JavaScript file from one JavaScript file. But for Node.js, there is no HTML page that starts it all. In the absence of the enclosing HTML page, Node.js uses its own module system based on CommonJS to put together multiple JavaScript files. Modules are like libraries. You can include the functionality of another JavaScript file (provided it’s written to follow a module’s specifications) by using the keyword require (which you won’t find in a browser’s JavaScript). You can therefore split your code into files or modules for the sake of better organization, and load one or another using require. There is a cleaner way to modularize your code using Node.js. Node.js ships with a bunch of core modules compiled into the binary. These modules provide access to the operating system elements such as the file system, networking, input/output, etc. They also provide some utility functions that are commonly required by most programs. Apart from your own files and the core modules, you can also find a great amount of third-party open source libraries available for easy installation. This brings us to npm.

Node.js Is Event Driven:

Node.js has an asynchronous, event-driven, non-blocking input/output (I/O) model, as opposed to using threads to get multitasking. Most languages depend on threads to do things simultaneously. But in fact, there is no such thing as simultaneous when it comes to a single processor running your code. Threads give the feeling of simultaneousness by letting other pieces of code run while one piece waits (blocks) for some event to complete. Typically, these are I/O events such as reading from a file or communicating over the network. For a programmer, this means that you write your code sequentially. For example, on one line, you make a call to open a file, and on the next line, you have your file handle ready. What really happens is that your code is blocked while the file is being opened. If you have another thread running, the operating system or the language can switch out this code and start running some other code during the blocked period. Node.js, on the other hand, has no threads. It relies on callbacks to let you know that a pending task is completed. So, if you write a line of code to open a file, you supply it with a callback function to receive the results. On the next line, you continue to do other things that don’t require the file handle. If you are accustomed to asynchronous Ajax calls, you will immediately know what I mean. Event-driven programming is natural to Node.js due to the underlying language constructs such as closures. Node.js achieves multitasking using an event loop. This is nothing but a queue of events that need to be processed and callbacks to be run on those events. In the above example, the file that is ready to be read is an event that will trigger the callback you supplied while opening it. On one hand, an event-based approach makes Node.js applications fast and lets the programmer locks that are utilized to synchronize multi-threaded events. On the other hand, getting used to this model takes some learning and practice.

Node.js and Npm

npm is the default package manager for Node.js. You can use npm to install third-party libraries (packages) and also manage dependencies between them. The npm registry (www.npmjs.com) is a public repository of all modules published by people for the purpose of sharing. Although npm started off as a repository for Node.js modules, it quickly transformed into a package manager for delivering other JavaScript-based modules, notably those that can be used in the browser. jQuery, by far the most popular client-side JavaScript library, is available as an npm module. In fact, even though React is largely client-side code and can be included directly in your HTML as a script file, it is recommended instead that React is installed via npm. But, once installed as a package, we need something to put all the code together that can be included in the HTML so that the browser can get access to the code. For this, there are build tools such as browserify or webpack that can put together your own modules as well as third-party libraries in a bundle that can be included in the HTML.

3- Express

Node.js is just a runtime environment that can run JavaScript. To write a full-fledged web server by hand on Node.js directly is not that easy, nor is it necessary. Express is the framework that simplifies the task of writing your server code. The Express framework lets you define routes, specifications of what to do when a HTTP request matching a certain pattern arrives. The matching specification is regular expression (regex) based and is very flexible, like most other web application frameworks. The what-to-do part is just a function that is given the parsed HTTP request. Express parses request URL, headers, and parameters for you. On the response side, it has, as expected, all of the functionality required by web applications. This includes setting response codes, setting cookies, sending custom headers, etc. Further, you can write Express middleware, which are custom pieces of code that can be inserted in any request/response processing path to achieve common functionality such as logging, authentication, etc. Express does not have a template engine built in, but it supports any template engine of your choice such as pug, mustache, etc. But, for an SPA, you will not need to use a server-side template engine. This is because all dynamic content generation is done on the client, and the web server only serves static files and data via API calls. Especially with MERN stack, page generation is handled by React itself on the server side. In summary, Express is a web server framework meant for Node.js, and it is not very different from many other server-side frameworks in terms of what you can achieve with it

4- MongoDB

MongoDB is the database used in the MERN stack. It is a NoSQL document-oriented database, with a flexible schema and a JSON-based query language.

Document-Oriented:

Compared to relational databases where data is stored in the form of relations, or tables, MongoDB is a document-oriented database. The unit of storage (comparable to a row) is a document, or an object, and multiple documents are stored in collections (comparable to a table). Every document in a collection has a unique identifier by which it can be accessed. The identifier is indexed automatically. Imagine the storage structure of an invoice, with the customer name, address, etc. and a list of items (lines) in the invoice. If you had to store this in a relational database, you would use two tables, say, invoice and invoice_lines, with the lines or items referring to the invoice via a foreign-key relation. Not so in MongoDB. You would store the entire invoice as a single document, fetch it, and update it in an atomic operation. This applies not just to line items in an invoice. The document can be any kind of deeply nested object. Modern relational databases have started supporting one level of nesting by allowing array fields and JSON fields, but it is not the same as a true document database. MongoDB has the ability to index on deeply nested fields, which relational databases cannot do. The downside is that the data is stored denormalized. This means that data is sometimes duplicated, requiring more storage space. Also, things like renaming a master (catalog) entry name would mean sweeping through the database. But then, storage has become relatively cheap these days, and renaming master entries are rare operations

NoSQL:

NoSQL stands for “non-relational,” no matter what the acronym expands to. It’s essentially not a common database where you have tables and columns (called a relational database). I find that there are two attributes of NoSQL that differentiate it from the conventional. The first is the ability to horizontally scale by distributing the load over multiple servers. NoSQL databases do this by sacrificing an important (for some) aspect of the traditional databases: strong consistency. That is, the data is not necessarily consistent for very brief amounts of time across replicas. For more information, read up on the “CAP theorem” (https://en.wikipedia.org/wiki/CAP_theorem). But in reality, very few applications require web scale, and this aspect of NoSQL databases comes into play very rarely. The second, and to me, more important, aspect is that NoSQL databases are not necessarily relational databases. You don’t have to think of your data in terms of rows and columns of tables. The difference in the representation in the application and on disk is sometimes called impedance mismatch. This is a term borrowed from electrical engineering, and it means, roughly, that we’re not talking the same language. In MongoDB, instead, you can think of the persisted data just as you see it in your application code; that is, as objects or documents. This helps a programmer avoid a translation layer, whereby one has to convert or map the objects that the code deals with to relational tables. Such translations are called object relational mapping (ORM) layers.

JavaScript Based:

MongoDB’s language is JavaScript. For relational databases, there is a query language called SQL. For MongoDB, the query language is based on JSON: you create, search for, make changes, and delete documents by specifying the operation in a JSON object. The query language is not English-like (you don’t SELECT or say WHERE), and therefore much easier to construct programmatically. Data is also interchanged in JSON format. In fact, the data is natively stored in a variation of JSON called BSON (where B stands for Binary) in order to efficiently utilize space. When you retrieve a document from a collection, it is returned as a JSON object. MongoDB comes with a shell that is built on top of a JavaScript runtime like Node.js. This means that you have a powerful and familiar scripting language (JavaScript) to interact with the database via command line. You can also write code snippets in JavaScript that can be saved and run on the server (the equivalent of stored procedures)

Schema-Less:

Storing an object in a MongoDB database does not have to follow a prescribed schema. All documents in a collection need not have the same set of fields. This means that, especially during early stages of development, you don’t need to add/rename columns in the schema. You can quickly add fields in your application code without having to worry about database migration scripts. At first, this may seem a boon, but in effect all it does is transfer the responsibility of data sanity from the database to your application code. I find that in larger teams and more stable products, it is better to have a strict or semi-strict schema. Using object document mapping libraries such as mongoose alleviates this problem.

Important Tools and Libraries:

It’s hard to build any web application without using tools to help you on your way. Here’s a brief introduction to the other tools apart from the MERN stack components that you will be very helpful for you to develop your applications

React-Router

React supplies only the view rendering capability and helps manage interactions in a single component. When it comes to moving between different views of the component and keeping the browser URL in sync with the current state of the view, we need something more. This capability of managing URLs and history is called routing. It is similar to the server-side routing that Express does: a URL is parsed, and based on its components, a piece of code is associated with the URL. React-Router not only does this, but also manages the browser’s history functionality so that we can move between what seem as pages without loading the entire page from the server. We could have built this ourselves, but React-Router is a very easy-to-use library that manages this for us.

Webpack:

Webpack is vital key when it comes to modularizing code. There are other competing tools such as Bower and Browserify which also serve the purpose of modularizing and bundling all the client code, but I found that webpack is easier to use and does not require another tool (like gulp or grunt) to manage the build process. We will be using webpack not just to modularize and build the client-side code into a bundle to deliver to the browser, but also to “compile” some code. The compilation step is needed to generate pure JavaScript from React code written in JSX

React-Bootstrap

Bootstrap, the most popular CSS framework, has been adapted to React and the project is called React-Bootstrap. This library not only gives us most of the Bootstrap functionality, but the components and widgets provided by this library also give us a a lot of information on how to design our own widgets and components. There are other component/CSS libraries built for React (such as Material-UI, MUI, Elemental UI, etc.) and also individual components . All these are good choices too, depending on what you are trying to get done. But I have found that React-Bootstrap is the most comprehensive single library with the familiarity of Bootstrap (which I presume most of you know already).

Why MERN?

So now you have a clear idea of the MERN stack and what it is based on. But is it really far superior to any other stack, say, LAMP, MEAN, J2EE, etc.? By all means, all of these stacks are good enough for most modern web applications. All said and done, familiarity is the crux of productivity in software, so I wouldn’t advise a MERN beginner to blindly start their new project on MERN, especially if they have an aggressive deadline. I’d advise them to choose the stack that they are already familiar with. But MERN does have its special place. It is ideally suited for web applications that have a large amount of interactivity built into the front-end. Go back and reread the section on “Why Facebook built React.” It will give you some insights. You could perhaps achieve the same with other stacks, but you’ll find that it is most convenient to do so with MERN. So, if you do have a choice of stacks, and the luxury of a little time to get familiar, you may find that MERN is a good choice.

JavaScript Everywhere:

The best part about MERN is that there is a single language used everywhere. It uses JavaScript for client-side code as well as server-side code. Even if you have database scripts (in MongoDB), you write them in JavaScript. So, the only language you need to know and be comfortable with is JavaScript. This is kind of true of all other stacks based on MongoDB and Node.js, especially the MEAN stack. But what makes the MERN stack stand out is that you don’t even need a template language to generate pages. In the React way, you programmatically generate HTML (actually DOM elements) using JavaScript. So, not only do you avoid learning a new language, you also get the full power of JavaScript. This is in contrast to a template language, which will have its own limitations. Of course, you will need to know HTML and CSS, but these are not programming languages, and there is no way you can avoid learning HTML and CSS (not just the markup, but the paradigm and the structure). Apart from the obvious advantage of not having to switch contexts while writing client-side and server-side code, having a single language across tiers also lets you share code between them. I can think of functions that execute business logic, do validation, etc. that can be shared. They need to be run on the client side so that user experience is better by being more responsive to user inputs. They also need to be run on the server side to protect the data model.

JSON Everywhere:

When using the MERN stack, object representation is JSON (JavaScript Object Notation) everywhere: in the application server, in the database and on the client, and even on the wire. I have found that this often saves my a lot of stress in terms of change. No object relational mapping (ORM), no having to force fit an object model into rows and columns, no special serializing and de-serializing code. An object document mapper (ODM) such as mongoose may help enforce a schema and make things even simpler, but the bottom line is that you save a lot of data transformation code. Further, it just lets me think in terms of native objects, and see them as their natural selves even when inspecting the database directly using a shell.

The npm Ecosystem:

I’ve already discussed the huge number of npm packages available freely for everyone to use. Any problem that you face will have an npm package already. Even if it doesn’t fit your needs exactly, you can fork it and make your own npm package. npm has been developed on the shoulders of other great package managers and has therefore built into it a lot of best practices. I find that npm is by far the easiest to use and fastest package manager I have used to date. The best part of npm is that most of the npm packages are so small, due to the compact nature of JavaScript code

Node.js Performance:

Due to its event-driven architecture and non-blocking I/O, the Node.js is very fast and a flexible web server. I have no doubt that when your application starts scaling and receiving a lot of traffic, this will play an important role in cutting costs as well as savings in terms of time spent in trouble-shooting server CPU and I/O problems.

It’s not a Framework!

Not many people like or appreciate this, but I really like the fact that React is a library, not a framework. A framework is assertive; it has a set way of doing things. The framework asks you to fill in difference of what it thinks you want to get done. A library, on the other hand, gives you tools to use to construct your application. In the short term, a framework helps a lot by getting most of the standard stuff out of the way. But over time, vagaries of the framework, its assumptions about what you want to get done, and the learning curve will make you wish you had some control over what’s happening under the hood, especially when you have some special requirements. With a library, an experienced architect can design his or her application with the complete freedom to pick and choose from the library’s functions, and build their own framework that fits their application’s unique needs. So, for an experienced Design or very unique application needs, a library is better, even though a framework can get you started quickly

Some awesome MERN Stack courses

1- MERN Stack React Node Ecommerce from Scratch to Deployment

MERN Stack React Node MongoDB powered E-Commerce App with PayPal and Credit Card Payment along with Admin Dashboard

Udemy Link: https://www.udemy.com/course/react-node-ecommerce/

Downoad Link: (Link)

2- MERN Stack Bootcamp — Zero to Hero in One Course

Master JavaScript React Node MongoDB NextJs SocketIo and Become a Professional MERN Stack Developer from Scratch

Udemy Link: https://www.udemy.com/course/mern-stack-bootcamp-react-node-socket-io/

Download Link: (Link)

3- Node.js, Express, MongoDB & More: The Complete Bootcamp 2021

Master Node by building a real-world RESTful API and web app (with authentication, Node.js security, payments & more)

Udemy Link: https://www.udemy.com/course/nodejs-express-mongodb-bootcamp/

Download Link: (Link)

Summary

This was a complete guide for those who want to start their career in MERN Stack and the technologies that are used in MERN Stack. If you like it please share it and don’t forget to like and comment.

--

--