Before any endpoint in a website is hit, there are some authorization checks to be made to make sure whatever is hitting the endpoint is valid and correct.
This is done by Middlewares which does 2 things mainly
For example the hospital-kidney example harkirat took,
Auth.1> kidney(s) >2 it is invalid → Validation. It is only valid when 1 ≤ kidney(s) ≤ 2.Middleware is just a function that is called in the main route that checks before the route goes to the final endpoint.
It uses the next() inbuilt function that chains the entire process of pre-checks together.
Here is how one can define middlewares, the following 1st middleware checks for the username and password if they are aryan and chodi@123 respectively. The second middleware checks if the kidney are in the range from 1 → 2 and finally the middlewares are used in app.get
function userMiddleware(req, res, next) {
const username = req.headers.username;
const password = req.headers.password;
console.log("USERNAME:", username);
console.log("PASSWORD:", password);
if(username !== "aryan" || password !== "chodi@123") {
res.status(403).json({
msg: "Invalid credentials",
});
} else {
next(); // this fucker is doing a threesome with userMiddleware + kidneyMiddleware
}
}
function kidneyMiddleware(req, res, next) {
const kidneyId = parseInt(req.query.kidneyId);
if(kidneyId != 1 && kidneyId != 2) {
res.status(404).json({
msg: kidneyId + " Kidneys not found!",
});
} else {
next();
}
}
app.get("/kidney-check", userMiddleware, kidneyMiddleware, (req, res) => {
res.send("Your kidney is good bruther!");
})
app.get("/username-check", userMiddleware, (req, res) => {
res.send("Username and Password are correct")
})
app.listen (3000, () => {
console.log("Server is running on PORT 3000")
})
If one writes app.use(middleware1), all the Restful APIs below it obtain the middleware by default without specifying it in the input argument beside the route.
Fun fact is that we use app.use(express.json()) which is also a middleware that checks if the body is compatible because sometimes when I send a request, the body tag is not compatible and the response shows me an error.
If there is any exception while sending a req, the backend can crash and spit out location information or configuration errors. People use this to exploit the service to get access to the backend calls potentially paid services for free, etc.
This is why global catches are used, to secure the backend of the server.
A Middleware that has 4 arguments - (err, req, res, next)is used to create these catches, which are used for exception and error handling.
Where are these used:
app.use((err, req, res, next) => { // exception handling
res.json({
msg: "Sorry bhai pata nai :(",
});
});