“Mastering Middleware-Based Input Validation in Node.js and Express”
abdulrehman rafique
Backend Engineer | JavaScript, Node.js, MongoDB | I Help Businesses Build Secure, Scalable Microservices & RESTful APIs on AWS, Handling 1M+ Users With 99.9% Uptime
You will learn how to use middleware functions to validate data for CRUD operations and handle errors gracefully.
By the end of this tutorial, you will be able to write clean and robust code for your Express API using middleware. Let’s get started!
In modern web development, the security of data flowing through your API is critical. Imagine a user submits a request to your Node.js and Express application with missing or malformed data. Without effective validation, this data could cause errors, security issues, or even compromise your application’s stability. In this article, we’ll explore a powerful approach to input validation using middleware — an efficient solution to ensure clean, secure data before it reaches your application logic.”
Old method for input validation:
we simple create a validation function using joi or anyother input validation npm package, and then import this validation function in controllers file and inside the controller call this validation function so drawback of this technique is Controllers code also executes and we dont need for controller execution at this point so it can slow down the application.
professional method for input validation:
In this method we validate the input request in middleware before reaching to controllers.. 1) First create a validation folder and inside this folder create a schema for validation that shown below.
const joi=require('joi');
const Validation = {
auth: {
signUp: {
body:joi.object({
name:joi.string().min(5).required(),
email:joi.string().email().required(),
password:joi.string().min(8).required()
})
},
login:{
body:joi.object({
email: joi.string().email().required(),
password: joi.string().min(8).required(),
})
}
}
}
module.exports = {Validation}
2) Create a middleware function that takes one argument in the form of schema,and inside this middleware function we will extract the user input that comes in request object and then validate the userinput with the schema if the validation will true then it moves to the controller for further processing otherwise it returns.Example of middleware function below.
const validate = (validation) => async (req,res,next) => {
try {
const data = req["body"]
const schema = validation["body"].required().label("body")
const value = await schema.validateAsync(data)
req.bodyValue = value
} catch (error) {
if(error.details){
const {message} = error.details[0]
next(new errorhandler(message,400))
}
}
return next();
}
module.exports = {validate}
3) In routes folder… router.post(“/login”,validate(Validation.auth.login),usercontroller.loginuser) when user request on this endpoint we first call the validate middleware function and pass the schema (validation.auth.login) and middlware first process the input request before passing it to controllers.
I have tried my best and hope I covered enough to explain it in detail so that you can get started.
If you encounter any problems, feel free to get in touch or comment below. I would be happy to help :)