Mastering Express.js Middleware

Mastering Express.js Middleware

Middlewares in express js are the functions which are used for performing tasks and handling routes via request response cycles. These functions can modify the request response objects, terminate req res cycle or pass control to the middleware function in the stack. Middleware functions are used to perform the actions such as authentication, logging, data parsing and error handling.

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

const MiddlewareFuncA = (req, res, next) => {
  console.log("Middleware Function 1");
  next();
};

const MiddlewareFuncB = (req, res, next) => {
  console.log("Middleware Function 2");
  next();
};

app.get("/middleware", MiddlewareFuncA, MiddlewareFuncB, (req, res) => {
  res.send("The above are the position of the middleware functions");
});
app.listen(3000);

// TO reproduce install express 
// write the above code in the editor
// spin the node server 
// go to the brower at "http://localhost:3000/middleware"
// the above logs will be triggered

Next in middleware

The "next()" function is a callback function that is passed to each middleware function in the stack.

fucntion middleWare (req, res, next){
    console.log('Middleware executed');
    next();
};
app.use(middleWare)  //app.use() function is used for the global
// execution of a certain function in this case middleware()

When next is called, it passes control to the next middleware function. If the "next" function is not called, the request-response cycle is terminated, and the response is sent back to the client.

In the above example, when a request is received, the middleWare() function is executed. After performing its tasks, it calls 'next()' to pass control to the next middleware in the stack.

Types and examples of middlewares

Logger Middleware

Logs the information about each incomming request, such as the request method, url, and timestamps

function Logger(req, res, next){
    console.log(`${req.method} ${req.url} - ${new Date()}`);
    next()
}
app.use(Logger);

Body Parser Middleware

Parses the request body, making it accessible through `req,body`

const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));

CORS Middleware

Handles Cross-Origin Resource Sharing issues, allowing or restricting access to resources on different domains.

const cors = require('cors');
app.use(cors());

Authentication Middleware

Auth middleware verifies the authenticated user by checking the token credentials before allowing the access to protected routes.

const authentication =(req, res, next)=>{
    if(authenticated){
    next();
    }else{
    res.status(411).send("Unauthorised")
    }
}

app.get('/route', authentication, (req, res)=>{
    res.send("Authenticated user");
})

Error Handling Middleware

This middleware helps to catch the errors and prevents app from crashing

app.use((error, req, res, next)=>{
    res.status(500).send('Something went wrong');
});

Session Middleware

Manages user sessions and maintains session state across requests.

const session = require('express- session');
app.use(session({secret:'secret-key', resave: true, saveUninitialized:true}));

Compression Middleware:

Compresses response data before sending it to the client to reduce bandwidth.

const compression = require('compression');
app.use(compression());

These are just a few examples, and middleware functions can be customized or created to suit the specific needs of an application. They provide a modular and flexible way to handle different aspects of request processing in a web application