DEV Community

harshchandwani
harshchandwani

Posted on

Understanding Middlewares

Hello Coders! Hope you are getting no bugs in the code, today, I want to share a little bit about what I am learning in MIDDLEWARES, as the name suggests, it is something that comes into the middle. It is the pre-computing of something. Let's take an example and understand.

const express = require("express");
const app = express();
function userMiddleware(req, res, next) {
    const username = req.headers.username;
    const password = req.headers.password;

    if (username !== "carlover" || password !== "carpassion") {
        res.status(403).json({
            msg: "User doesn't exist",
        });
        return;
    } else {
        next();
    }
}
function carMiddleware(req, res, next) {
    const carId = req.query.carId;

    if (carId !== "sedan" && carId !== "suv") {
        res.status(411).json({
            msg: "Wrong car type",
        });
        return;
    } else {
        next();
    }
}
app.get("/car-checkup", userMiddleware, carMiddleware, function (req, res) {
    // do health checks here
    const carId = req.query.carId;

    //Do something with the car here
    res.json({
        msg: `Your ${carId} is in great condition!`
    });
});

app.listen(3000, () => {
    console.log("Ready");
});
Enter fullscreen mode Exit fullscreen mode

Here we have 2 functions, userMiddleware and carMiddleware,
and we are calling the functions in the app.get, why because we want to pre-check the same as we will only get into the 3rd function when the 2nd function is successfully computed and the 2nd will only compute when the 1st will be successfully computed.

But where do we use Middlewares?

Authentication: Middlewares can validate user credentials, ensuring only authorized users access protected routes, and enhancing application security.

Logging: Implementing logging middleware helps track requests, errors, and user activities, aiding in debugging and performance monitoring.

Data Validation: Middlewares validates incoming data, ensuring it adheres to specified formats or rules, preventing invalid or malicious inputs from impacting the application.

CORS Handling: Middleware can manage Cross-Origin Resource Sharing (CORS), permitting or restricting resource access based on defined policies, and enhancing web application interoperability.

Top comments (0)