Switching to the Modern Day MERN stack!

Dhairya Patel
Nybles
Published in
15 min readJul 4, 2019

Life and websites have grown tremendously since those plain sailing times. Websites have moved on from simple rotating GIFs and tables to mobile responsive, widget based features that load rapidly. What used to be a combination of mere HTML, CSS and some dreadful java script no longer suffices hunger of mankind. Users increasingly demand a far richer experience from the web sites. At the same time, there’s pressure on developers to deliver new applications faster and continually roll-out enhancements, while ensuring that the application is highly efficient and can be scaled appropriately when needed, compelling developers to adopt a (sometimes bewildering) set of technologies collectively called a stack, to make all that possible.

Who’s this for?

Anyone who is not yet exposed to the miracles of web technology, anyone who wants to adopt MERN stack (may be a complete newbie !) or anyone who is ready to invest some precious time.

Prerequisites

A sound body ,an open mind and knowledge of superficial programming concepts is all that is required.

What to expect from this article?

A basic understanding and introduction of each component of the MERN stack and the associated technologies.Please don’t expect to become a full stack developer by solely reading this article but I can assure you that this investment can take you one step closer .

Let’s begin

A stack is the combination of technologies used to create a web application. Any web application will be made using multiple technologies (frameworks, libraries, databases etc).

The MERN stack is a JavaScript stack that’s designed to make the development process smoother. MERN includes four entirely open-source components: MongoDB, Express, React, and Node.js. Adopting the stack also addresses critical but repetitive development tasks that redirects efforts towards building and innovating upon a breakthrough application and its testing. Another useful aspect of using MERN stack is developing Single Page Applications(SPA).

What is SPA?

An SPA is a web application paradigm that avoids refreshing a web page to display new contents instead uses lightweight calls to the server to get some data or snippets and updates the web page i.e, re-renders only that part of the page which has changed instead of rendering all the pixels of the page again. The result looks quite nifty as 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.

A Closer Look at MERN Stack Components

MongoDB

MongoDB is a NoSQL document-oriented database. It has flexible schema and json (Java Script Object Notation) based query language.

NoSQL stands for ‘non-relational’ SQL. It is essentially not a conventional database where you have tables and columns, called relational databases. There are actually two attributes of NoSQL that differentiate them from conventional.

The first is their ability to horizontally scale by distributing the load over multiple servers. They do this by sacrificing an important aspect of traditional databases i.e, strong consistency. But in reality very few applications require strong consistency and this aspect of NoSQL databases comes into play very rarely.

The second is that the data can be visualised to be stored in terms of an array of objects. Each individual element of the array is called document. It is possible that two elements have different sets of properties (that is why it is inconsistent or schema-less). The unit of storage is therefore, document and multiple documents are stored collectively as a collection(analogous to table in SQL). The document can be any kind of deeply nested object.

Every document in a collection has a unique identifier using which it can be accessed. This is generally a property named ‘_id’. The identifier is indexed automatically. It is a 12 byte value with the following distribution:first 4 bytes -time stamp, next 3 bytes-machine identifier, next 2 bytes-process id and the remaining 3 bytes are counter. One great feature here is that we can extract time stamp to know exactly when a document was created. MongoDB also provides us ways to create id’s whenever we want to extend its use.

The downside is that the data is stored de-normalised. This means that data is sometimes duplicated, requiring more storage space. In large applications it is better to have a strict or semi-strict schema. Using Object Document Mapping libraries such as mongoose(which you will come across when you will actually start learning to code and therefore not covered here)solves the problem.

MongoDB’s language is JavaScript. For relational databases, we had a query language called SQL. For MongoDB, the query language is based on json. The query language is not English-like (you don’t SELECT or say WHERE), and therefore much easier to construct pro grammatically. 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 utilise space. When you retrieve a document from a collection, it is returned as a json object. It also comes with a shell which is built on top of a JavaScript run-time like Node.js. This means that you have a powerful and familiar scripting language (JavaScript) to interact with the database via command line.

Express

Express is just a web framework for Node.js. Node.js is just a run-time environment that can run java-script. To write a full-fledged web server by hand on Node.js directly is not that easy, neither is it necessary. Express is that 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 functionality required by web applications. This includes setting response codes, setting cookies, sending custom headers etc. Further, you can write Express middle ware( we will come across middle ware later in this article), custom pieces of code that can be inserted in any request / response processing path to achieve common functionality such as logging, authentication etc. All these features are provided through different plugins.

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.

React

React anchors the MERN stack. In some sense, this is the defining component of the MERN stack. It is an open-source java-script library maintained by Facebook that can be used for creating views rendered in HTML. Remember the SPA’s where only the part which is changed is re-rendered instead of entire page, React is solely responsible for such behaviour. The best example of this is the web whatsapp.

It is recommended to install React Developer Tools from the chrome web store for its useful features which assists us in the process of development. Another feature is that the extensions logo glows when we open a website using react. Have a look at the top right corner !

Logo glows on Web Whatsapp
Logo does not glow on twitter

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. How does this work?

A React component declares how the view looks like, given the data. You just don’t do anything! The React library figures out how the new view looks like, and just applies the changes between the old view and the new view. This makes the views consistent, predictable and easier to maintain and simpler to understand.

Won’t this be too slow? Will it not cause the entire screen to be refreshed or re-render on every data change? Well, React takes care of this using its Virtual DOM technology. You declare how the view looks like 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 does only the required DOM changes, this adds very little overhead because the algorithm to compute the differences in the Virtual DOM has been optimised to the hilt.

Component-Based

The fundamental building block of React is a Component that 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 depicts 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 call backs 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.

There is an intermediate language to represent a Virtual DOM, and that is JSX, which is very similar to HTML. JSX stands for Java-script XML and is a syntax extension and is not present in core JavaScript language.

You don’t have to use JSX, you can write pure JavaScript to create your virtual DOM if you prefer. But it is recommended to use JSX for its simplicity.

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 we introduce Node.js.

Node.js

Node.js is a java-script run-time that uses the chrome’s V8 engine which is an open source java script run-time written in C++, that takes JS code and compiles it to machine code.

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 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 Common JS 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 organisation, and load one another using require.

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. That brings us to npm.

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 is a public repository of all modules published by people for the purpose of sharing.

Though 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, we have 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.

Middleware

You can assume middle ware as a means to add currently not existing functionality to node to get work done.

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 achieve multi-tasking.

Most other 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 simultaneous 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 or API calls. 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 used 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 multi-tasking 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 being ready to be read will be an event which will trigger the callback you supplied while opening it.

you can visualise in this manner

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 will be useful during development purpose

React-Router

React gives us only the View rendering capability and helps manage interactions in a single component. When it comes to transitioning 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. This is similar to 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 Back button functionality so that we can transition between what seem as pages without loading the entire page from the server.

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 wealth of information on how to design our own widgets .

Babel

Remember the JSX we discussed earlier. The problem with it is that the browser doesn't know how to interpret it. So we need a compiler. Hence Babel.It is a free and open-source JavaScript compiler used in web development.

Webpack

Webpack is an open-source JavaScript module bundler. It is a module bundler primarily for JavaScript, but it can transform front-end assets like HTML, CSS, and images if the corresponding plugins are included. Webpack takes modules with dependencies and generates static assets representing those modules.

create-react-app

The problem initially with react is to configure it and tools like babel,webpack, associated styles which becomes a night mare.In this most of the cases this tools come handy. By just running one command all this tools are preconfigured and hidden so that you can focus on the code.

Other Libraries

Very often, we’ll feel the need for a library to address a seemingly common problem that all of us would face. Most commonly used ones are body-parser (to parse POST data in the form of JSON, or form data) for node, mongoose and mongodb native for database, cors,morgan etc. Do not worry you would come across each of this as you dive deep inside.

Why MERN?

Interactivity

MERN stack is ideally suited for web applications that have a large amount of interactivity built into the front-end.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 that I like is that there is a single language used everywhere. We use 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 at the back-end, 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

JSON everywhere

When using the MERN stack, object representation is JSON (JavaScript Object Notation) everywhere — in the database, in the application server and on the client, and even on the wire.

I have found that this often saves me a lot of hassle in terms of transformations. No Object Relational Mapping (ORM), not having to force fit an object model into rows and columns, no special serializing and de-serialising 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.

Node.js Performance

Due to its event driven architecture and non-blocking I/O, the claim is that Node.js is very fast and a resilient web server. Although it takes a little getting used to, but when your application starts scaling and receiving a lot of traffic, this will play an important role in cutting costs and savings in terms of time spent in trouble-shooting server CPU and I/O problems.

That’s it for this one. It’s not complete information but hopefully it’s enough to get you started and understanding how these technologies all tie together and igniting in you the desire to learn them. Since these are very popular technologies, there are tons of resources available which will guide you in the learning process. There is definitely a long road to cover. I hope you find this helpful.

Enjoy Learning :)

Thank You !

About me: Hey I am Dhairya , an undergrad student here at Indian Institute of Information technology, Allahabad. Interested in food, some music, full stack web development and machine learning.

Thanks for reading! If you enjoyed this story, please click the 👏 button and share to help others find it! Feel free to leave a comment 💬 below.

--

--