Express Zod Safe

express-zod-safe
is a strict, type-safe middleware designed for Node.js applications, leveraging the robustness of Zod schemas to validate incoming request bodies, parameters, and queries. This package seamlessly integrates with Express.js to provide developers with a type-safe, declarative approach to ensure data integrity and prevent invalid or malicious data from affecting their applications.

Reducing Verbosity
The goal of express-zod-safe
was to provide a pretty terse API that validated and typed requests. Traditionally, these two would be separate activities, but there's no reason why they can't be combined. In fact, combining, the two, zod
validation with inference is the easiest way to make sure that they both stay in sync. In other words, the types a developer uses at build time are the types they will see in production, no matter what the user inevitably ends up inputting. Here's a relatively feature complete example validating, the request body, query and path parameters.
1import express from 'express';
2import validate from 'express-zod-safe';
3import { z } from 'zod';
4
5const app = express();
6app.use(express.json());
7
8// Define your Zod schemas
9const params = {
10 userId: z.string().uuid(),
11};
12const query = {
13 age: z.coerce.number().optional(), // Given all query params and url params are strings, this will coerce the value to a number.
14};
15const body = {
16 name: z.string(),
17 email: z.string().email(),
18};
19
20// Use the validate middleware in your route
21app.post('/user/:userId', validate({ params, query, body }), (req, res) => {
22 // Your route logic here
23 res.send('User data is valid!');
24});
25
26app.listen(3000, () => console.log('Server running on port 3000'));
The library also accommodates more commonly requested features such as global/route-specific custom error handlers, allowing the developer to customise whether or how errors are logged and displayed to end users.
Community & Contributions
Initially created a personal project to reuse the same validation logic and typing I was creating across different projects, the library has since garnered a lot of traction amongst the community. With 4,000 downloads a week and growing, it is one of my most widely used open source software publications. This community engagement has also had the benefit of introducing new contributors to the project as users encounter issues or take it upon themselves to propose and implement new features. If you're interested in using this project, or contributing yourself, please check it out on GitHub.