π§ Understanding Middlewares, Global Catches & Input Validation (with Zod) in Node.js

Table of contents
Imagine visiting a hospital. Before you meet the doctor, you go through multiple checks:
- Insurance validation
- Blood test
- BP check
Only if you pass all of these, you get to meet the doctor.
In the world of web development, your API routes are like the doctor's cabin. And all these checks? They're called middlewares.
Letβs break it down in easy terms π
π§© What is a Middleware?
Middleware is just a function that runs before your main route handler.
They are useful for:
- Authentication (Is this user allowed?)
- Input validation (Did the user send correct data?)
- Logging, analytics, etc.
Example
import express from 'express';
const app = express();
// Custom middleware
const authMiddleware = (req, res, next) => {
const { username, password } = req.headers;
if (username === 'admin' && password === '1234') {
next(); // Proceed to the next middleware or route
} else {
res.status(403).json({ error: 'Unauthorized access' });
}
};
app.use(express.json());
app.get('/kidney-check', authMiddleware, (req, res) => {
res.json({ message: 'Kidneys are healthy!' });
});
app.listen(3000);
π Reuse logic across multiple routes
You can write a middleware once and use it across routes, instead of repeating the same if
checks every time.
β οΈ Global Catches
Sometimes, your app might crash due to a coding mistake or invalid input. You can catch these errors globally and show a proper message instead of a full app crash.
Global Error Handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
Add this at the bottom of all your routes to catch any uncaught errors in your app.
π‘ Validating Inputs with Zod
Manually checking if the user has sent correct data (like numbers, emails, etc.) is tiring.
Thatβs where Zod comes in.
Zod is a TypeScript-first schema validation library that makes it super easy to validate inputs.
Example
import { z } from 'zod';
const userSchema = z.object({
name: z.string(),
age: z.number().min(18), // Must be at least 18
});
app.post('/register', (req, res) => {
const result = userSchema.safeParse(req.body);
if (!result.success) {
return res.status(400).json({ error: result.error.errors });
}
res.json({ message: 'User registered successfully!' });
});
Benefits:
- Less code to write
- Super readable
- Works great with TypeScript
π Real-Life Use Case: Kidney API
Say we have a route /kidney
that checks if a person has a valid kidney ID.
Requirements:
kidneyId
in query param (must be 1 or 2)username
andpassword
in headers
Middleware-based Approach
// Middleware to check kidneyId and auth
const validateKidneyRequest = (req, res, next) => {
const kidneyId = Number(req.query.kidneyId);
const { username, password } = req.headers;
if (kidneyId !== 1 && kidneyId !== 2) {
return res.status(400).json({ error: 'Invalid kidneyId' });
}
if (username !== 'admin' || password !== '1234') {
return res.status(403).json({ error: 'Unauthorized' });
}
next();
};
app.get('/kidney', validateKidneyRequest, (req, res) => {
res.json({ message: 'Kidney is valid!' });
});
π Authentication with JWT (a sneak peek)
Instead of passing username and password in every request (which is insecure), use JWT (JSON Web Tokens):
- User logs in β you give them a token
- They send the token in headers
- You validate the token in your middleware
(Weβll cover this more in a future blog)
π Summary
- Middlewares are like security checks before reaching your route.
- Global catches help you catch all errors in one place.
- Zod makes input validation clean and scalable.
β Bonus: Practice Tasks
Try making middlewares for:
- Counting how many requests are coming to your server
- Measuring how long each request takes to complete
Feel free to reach out if you'd like a follow-up post on JWT auth, error handling patterns, or rate limiting!
Subscribe to my newsletter
Read articles from Nikhil Sinha directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Nikhil Sinha
Nikhil Sinha
I am a Student pursuing a Master's in Computer application. I have experience in making Frontend projects. I worked on React, and JavaScript and currently learning Node for Backend. In his free time, he likes to contribute to open source. Apart from that he is also a Technical Blogger.