Table of contents
Middleware
Middleware refers to a software design pattern where functions are invoked sequentially in a pipeline to handle requests and responses in web applications.
Middleware functions are JavaScript functions that have access to the request object (req
), response object (res
), and the next middleware function in the pipeline (next
).
Lets create a basic express server.
const express = require('express')
const app = express()
app.get('/health-checkup',function(req,res){
res.send('I am healthy')
})
app.listen(3000);
How do you do auth checks? how to ensure the user input is valid?
Use middleware
Lets create a middleware that does a basic authentication check and and input validation.
const express = require('express')
const app = express()
app.use(express.json())
function userMiddleware(req,res,next){
username=req.headers.username
password=req.headers.password
if (username!='reuben' && password!='pass'){
res.status(401).send('Unauthorized')
}else{
next()
}
}
function kidneyMiddleware(req, res ,next){
kidneyId=req.query.kidneyId
if(kidneyId==1 || kidneyId==2){
next()
}else{
res.status(400).send('Bad kidneys')
}
}
app.get('/health-checkup', userMiddleware, kidneyMiddleware, function(req,res){
res.send('I am healthy')
})
app.listen(3000);
Global Catches
What if the user sends the wrong body?
Global catches help you provide the user with a better error message.
Let's create a middleware that reads the number of kidneys.
const express = require('express')
const app = express()
app.use(express.json())
app.post('/health-checkup', function(req,res){
const kidneys = req.body.kidneys
const kidneyLength = kidneys.length;
res.send('No. of kidneys: '+kidneyLength)
})
app.listen(3000);
Let's send invalid input
Ugly error output.
const express = require('express')
const app = express()
app.use(express.json())
app.post('/health-checkup', function(req,res){
const kidneys = req.body.kidneys
const kidneyLength = kidneys.length;
res.send('No. of kidneys: '+kidneyLength)
})
app.use((err, req, res, next)=>{
res.status(500).send('Invalid inputs')
})
app.listen(3000);
Define error-handling middleware functions in the same way as other middleware functions, except error-handling functions have four arguments instead of three: (err, req, res, next)
.
Zod Validation
Zod is a TypeScript-first schema declaration and validation library. It's used primarily for validating data against a schema, ensuring that the data conforms to the specified structure and constraints.
const express = require('express')
const app = express()
const { z } = require("zod");
const emailSchema = z.string().email("Invalid email");
const passwordSchema = z.string().min(6, "Password must be at least 6 characters");
function validateCredentials(req,res,next) {
const email = req.headers.email;
const password = req.headers.password;
emailSchema.parse(email);
passwordSchema.parse(password);
next()
}
app.get('/health-checkup',validateCredentials,function(req,res){
res.send("Health Checkup is done successfully")
})
app.listen(3000);