What is MERN Stack? A beginners Guide

What is MERN Stack? A beginners Guide

ยท

5 min read

MERN stack simply stands for a combination of 4 different tech stacks.

M-MongoDB

MongoDB is a source-available cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas

This is what we use for our database

MongoDB logo and symbol, meaning, history, PNG

E-Express.JS

Express.js, or simply Express, is a back end web application framework for building RESTful APIs with Node.js, released as free and open-source software under the MIT License

This is where our Backend (written in Js) is going to be run from

Express.js Tutorial for Beginners | Learn Express ...

R-React JS

React lets you build user interfaces out of individual pieces called components. With React you can create your own React components like Thumbnail, LikeButton, and Video. Then combine them into entire screens, pages, and apps.

With React, this is what our FrontEnd is fully based on.
Currently, there is even a framework made off of React.js ; NextJs which also has some server-side functionalities
Not only can react use JavaScript, With Vite+React template, we can be able to use React Typescript ๐Ÿš€๐Ÿš€

How does MERN technologies work?

Before we spin up an example of a MERN project, it is crucial for us to get to understand how this combination works.

  • The frontend, developed with React.js, communicates with the backend, developed with Express.js and Node.js, through HTTP requests.

  • Express.js defines API routes that handle these requests and interact with the MongoDB database to perform CRUD operations.

  • The data is retrieved from or stored in MongoDB and then sent back to the React.js frontend for display or further processing.

In the next section we are going to create a MERN application

MERN application example

  1. Setup MongoDB:

    • Install MongoDB and make sure it's running.

    • For Windows, Linux or MacOs you can get it from here

  2. Setup Express.js (Node.js Backend):

    • Initialize a new Node.js project: npm init -y

    • Oh by the way, make sure you have Node Installed in your machine

    • Install necessary packages by typing: npm install express mongoose cors in your terminal

  3. Create a basic Express server:

    Create an index.js file then copy and paste the snippet below:

     // index.js
     const express = require('express');
     const mongoose = require('mongoose');
     const cors = require('cors');
    
     const app = express();
     const PORT = process.env.PORT || 5000;
    
     app.use(cors());
     app.use(express.json());
    
     // Connect to MongoDB
     mongoose.connect('mongodb://localhost:27017/tasks', { useNewUrlParser: true, useUnifiedTopology: true });
    
     // Define Task Schema
     const taskSchema = new mongoose.Schema({
       title: String,
       description: String,
     });
    
     const Task = mongoose.model('Task', taskSchema);
    
     // CRUD operations
     app.post('/api/tasks', async (req, res) => {
       const task = new Task(req.body);
       await task.save();
       res.json(task);
     });
    
     app.get('/api/tasks', async (req, res) => {
       const tasks = await Task.find();
       res.json(tasks);
     });
    
     app.put('/api/tasks/:id', async (req, res) => {
       const task = await Task.findByIdAndUpdate(req.params.id, req.body, { new: true });
       res.json(task);
     });
    
     app.delete('/api/tasks/:id', async (req, res) => {
       const task = await Task.findByIdAndDelete(req.params.id);
       res.json(task);
     });
    
     app.listen(PORT, () => {
       console.log(`Server is running on port ${PORT}`);
     });
    
  4. Setup React.js (Frontend):

    • Create a new React app: npx create-react-app task-manager or use npm create vite@latest (Recommended)

    • Navigate to the project: cd task-manager

    • Install Axios for making HTTP requests: npm install axios (I prefer using Axios because of compatibility, but fetch method also works)

  5. Create a basic React app with CRUD functionality:

    Navigate to your folder/src then App.js / App.jsx and paste the snippet below:

     // src/App.js
     import React, { useState, useEffect } from 'react';
     import axios from 'axios';
    
     const App = () => {
       const [tasks, setTasks] = useState([]);
       const [newTask, setNewTask] = useState({ title: '', description: '' });
    
       useEffect(() => {
         axios.get('/api/tasks').then((response) => {
           setTasks(response.data);
         });
       }, []);
    
       const handleAddTask = () => {
         axios.post('/api/tasks', newTask).then((response) => {
           setTasks([...tasks, response.data]);
           setNewTask({ title: '', description: '' });
         });
       };
    
       const handleDeleteTask = (id) => {
         axios.delete(`/api/tasks/${id}`).then(() => {
           setTasks(tasks.filter((task) => task._id !== id));
         });
       };
    
       return (
         <div>
           <h1>Task Manager</h1>
           <ul>
             {tasks.map((task) => (
               <li key={task._id}>
                 {task.title} - {task.description}
                 <button onClick={() => handleDeleteTask(task._id)}>Delete</button>
               </li>
             ))}
           </ul>
           <input
             type="text"
             placeholder="Task title"
             value={newTask.title}
             onChange={(e) => setNewTask({ ...newTask, title: e.target.value })}
           />
           <input
             type="text"
             placeholder="Task description"
             value={newTask.description}
             onChange={(e) => setNewTask({ ...newTask, description: e.target.value })}
           />
           <button onClick={handleAddTask}>Add Task</button>
         </div>
       );
     };
    
     export default App;
    
  6. Run the application:

    • Start the backend server: node index.js

    • Start the React app: npm start (For CreateReactApp) or npm run dev (For Vite)

Now we have a simple MERN stack CRUD project for a task management app! You can expand and customize it based on your needs. ๐ŸŽ‰

Advantages of MERN approach

  1. Flexibility - you can be able to tweak either the front or backend without tampering with the whole application. For example I can decide to change my styling on the front end, and still my login functionalities will work
    I can also decide to add / strip off a feature like dark mode without fear of something not to work

  2. Fast development time - With MERN, React makes it easy to develop the FrontEnd then make a quick transition towards the BackEnd. In no time, the whole project gets done

    Wall Clock

  3. High performance - MERN stack apps are very fast ๐Ÿš€๐Ÿš€. I don't remember the last time someone mentioned of a slow MERN app ๐Ÿคฃ๐Ÿคฃ๐Ÿคฃ

Extensive Developer Ecosystem - OMG there are very many MERN stack specialized developers. This means if you need resources or get stuck, there is 99% chance to get a workaround. This is because a large number of devs know React and JavaScript is a popular language.

React Developer Skills: Requisites To Know Before Hiring

Limitations of MERN approach

  1. Learning Curve:

    For developers new to JavaScript or those unfamiliar with the entire MERN stack, there can be a steep learning curve. Learning multiple technologies simultaneously might be challenging for beginners.
    Let this not discourage you. If you already know a bit of REACT, you are ready to go ๐Ÿš€๐Ÿš€๐Ÿš€

  2. NoSQL constraints:
    Since we are using MongoDB, we may get into issues with complex relationships and transactional requirements

  3. Lack of Opinionation:

    While flexibility is an advantage, it can also be a drawback for teams that prefer more opinionated frameworks. Some developers may find it time-consuming to make decisions about libraries, tools, and project structure.

Conclusion

In a nutshell, MERN is a nice approach to creating FullStack web apps and it is becoming a very popular specialization among React Developers. It is nice and we should all strive to reap its benefits. (At least if the technologies are still supported)

ย