DEV Community

Cover image for Day 41 of Learning MERN stack
Ali Hamza
Ali Hamza

Posted on

Day 41 of Learning MERN stack

Hello Dev Community! 👋

It is officially Day 41 of my continuous streak toward full-stack MERN engineering! Yesterday, I migrated my codebase from native Node boilerplate to Express.js. Today, I dived straight into the absolute core mechanism that makes Express so incredibly powerful in Prashant Sir's (Complete Coding) masterclass: Middlewares.

Before today, I thought requests hit an endpoint and immediately returned a response. Today, I learned how to intercept, inspect, and modify that request before it ever reaches the final route handler!


🧠 Key Learnings From Node.js Lecture 9 (Middlewares)

A middleware is essentially a function that executes during the Request-Response cycle, having full access to the req, res, and the next middleware function in line. Here is the technical breakdown:

1. The Anatomy of Middleware

Unlike a standard route handler that takes (req, res), a middleware takes a third powerful argument: next. If you don't invoke next(), your request will hang forever and the browser will eventually timeout!

2. Built-in vs. Custom Middleware

  • Custom Middleware: Wrote my own custom functions using app.use((req, res, next) => { ... }) to act as a security guard or global logger.
  • Built-in Middleware: Explored how Express natively handles data types using structures like express.json() and express.urlencoded(), which automatically parse inbound request bodies so we don't have to manually handle streams anymore!

javascript
const express = require("express");
const app = express();

// Custom Global Logging Middleware
app.use((req, res, next) => {
    console.log(`[${new Date().toISOString()}] ${req.method} request to ${req.url}`);
    next(); // Pass control to the next handler in line!
});

app.get("/dashboard", (req, res) => {
    res.send("Welcome to the secure dashboard layer!");
});

app.listen(8000);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)