DEV Community

Cover image for Validating Request Data in Express.js using Zod and TypeScript: A Comprehensive Guide

Validating Request Data in Express.js using Zod and TypeScript: A Comprehensive Guide

Stephen Akugbe on January 15, 2024

Introduction Express.js is a popular web framework for building Node.js applications, and validation is a crucial aspect of handling inc...
Collapse
 
vigneshintech profile image
Vignesh Murugan

This is great, right to the point.
Thanks!!!!

Collapse
 
osalumense profile image
Stephen Akugbe

Thank you Vignesh

Collapse
 
adrielfsantos profile image
Adriel

Really useful, thanks!

Collapse
 
osalumense profile image
Stephen Akugbe

Thank you @adrielfsantos

Collapse
 
belloshehu profile image
Bello Shehu

Good one. Very concise

Collapse
 
ba2sik profile image
Ron Zano

Very nice!

Collapse
 
oppaaaii profile image
obei

amazing and simple thx

Collapse
 
hrithikraj1999 profile image
Hrithik Raj

Thanks

Collapse
 
caducoder profile image
Carlos Eduardo

How can i validate the params too? Great article, thanks!

Collapse
 
andonov85 profile image
andonov85

You can try something like this for a validation.middleware.ts:

import { RequestHandler } from 'express';
import { ZodTypeAny, z } from 'zod';

const validate = (
  schema: ZodTypeAny,
  source: 'body' | 'params' | 'query'
): RequestHandler => {
  return async (req, res, next) => {
    try {
      await schema.parseAsync(req[source]);
      next();
    } catch (err) {
      if (err instanceof z.ZodError) {
        res.status(400).json({
          message: `Invalid ${source} schema`,
          errors: err.errors,
        });
      } else {
        next(err);
      }
    }
  };
};

const validateRequestBody = (schema: ZodTypeAny): RequestHandler => {
  return validate(schema, 'body');
};

const validateRequestParams = (schema: ZodTypeAny): RequestHandler => {
  return validate(schema, 'params');
};

const validateRequestQuery = (schema: ZodTypeAny): RequestHandler => {
  return validate(schema, 'query');
};

export { validateRequestBody, validateRequestParams, validateRequestQuery };

Enter fullscreen mode Exit fullscreen mode
Collapse
 
landersonalmeida profile image
Landerson

Nice! thank you :)