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

Nikhil SinhaNikhil Sinha
3 min read

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 and password 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):

  1. User logs in β†’ you give them a token
  2. They send the token in headers
  3. 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!

1
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.