DEV Community

Discussion on: Schema Validation with Zod and Express.js

Collapse
 
brianmcbride profile image
Brian McBride

Obviously it's not something that's very generalized

I love how you said that. This is the trap that we fall in as developers.
While I always say use a well supported lib before going to write your own, the details of our best practices can be improved.

Why do we modify the Request object in Express? How do we expect the developer downstream to know what we added or changed? If we look at more opinionated frameworks, we start to see the use of a context object that is clearly typed and defined. The same javascript developer who extolls the virtue of immutability in their React state engine is the same person who will arbitrarily modify their backend Request source of truth.

I've personally wasted hours going "why doesn't this work" only to find out some middleware we put in was changing the request or response objects.

There is a functional pattern that you could use and it would be clearly declarative and let you modify the data as it passes from function to function and that is using RxJS. If we truly treat the HTTP request as a stream (which it is), RxJS unlocks a LOT. Most of the time, it is too much unless you use observables often and feel comfortable with them.

Outside of programming by tradition, the other advantage of what I've done above is that you get the coercing from zod. In your validation pattern, you aren't going to get defaults, have unwanted keys stripped from your objects, or have transformations applied.

const mySchema = z.object({
  query: z.object({
    page: z.number().optional().default(0),
    pageSize: z.number().optional().default(20),
  }),
});
const { params, query: {page, pageSize}, body } = await zParse(mySchema, req);
Enter fullscreen mode Exit fullscreen mode

Based on my schema, I know 100% that the query page is defined and it is a number with a default of 0 and pageSize is a number, is defined, and has a default of 20. Params will be undefined and body will be undefined.