Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/angablue/express-zod-safe
Typesafe middleware designed for Node.js applications, leveraging the robustness of Zod schemas to validate incoming request bodies, parameters, and queries.
https://github.com/angablue/express-zod-safe
Last synced: about 7 hours ago
JSON representation
Typesafe middleware designed for Node.js applications, leveraging the robustness of Zod schemas to validate incoming request bodies, parameters, and queries.
- Host: GitHub
- URL: https://github.com/angablue/express-zod-safe
- Owner: AngaBlue
- License: lgpl-3.0
- Created: 2024-01-08T04:26:52.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2024-12-31T04:33:29.000Z (about 1 month ago)
- Last Synced: 2025-01-31T06:18:32.338Z (6 days ago)
- Language: TypeScript
- Homepage:
- Size: 94.7 KB
- Stars: 9
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
🛡️ Express Zod Safe
Express Zod Safe is a strict, typesafe 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 (or similar frameworks) to provide developers with a typesafe, declarative approach to ensure data integrity and prevent invalid or malicious data from affecting their applications.
_This package was inspired by Aquila169's [zod-express-middleware](https://github.com/Aquila169/zod-express-middleware) package, and is intended to be a more robust and typesafe alternative._
## 🔒 Features
- **Typesafe**: Built with TypeScript, offering complete typesafe interfaces that enrich your development experience.
- **Zod Integration**: Utilizes Zod schemas for comprehensive and customizable request validation.
- **Middleware Flexibility**: Easily integrates with Express.js middleware stack, ensuring a smooth validation process without compromising performance.
- **Parameter & Query Validation**: Validates not just request bodies but also URL parameters and query strings, covering all facets of incoming data.
- **Error Handling**: Provides detailed, developer-friendly error responses to aid in debugging and informing API consumers.
- **Simple & Intuitive**: Designed to be easy to use and understand, with a declarative API that is both concise and powerful.## ⬇️ Install
Install this package using your package manager of choice.
```sh
npm i express-zod-safe
````zod`, `express` and `@types/express` are peer dependencies and must be installed separately. This means you can bring your own version of these packages, and this package will not force you to use a specific version.
```sh
npm i zod express && npm i -D @types/express
```## 🛠️ Usage
```ts
import express from 'express';
import validate from 'express-zod-safe';
import { z } from 'zod';
const app = express();
// Define your Zod schemas
const params = {
userId: z.string().uuid(),
};
const query = {
age: z.coerce.number().optional(), // Given all query params and url params are strings, this will coerce the value to a number.
};
const body = {
name: z.string(),
email: z.string().email(),
};
// Use the validate middleware in your route
app.post('/user/:userId', validate({ params, query, body }), (req, res) => {
// Your route logic here
res.send('User data is valid!');
});app.listen(3000, () => console.log('Server running on port 3000'));
```**Note:** The `validate` middleware must be used **after** any other middleware that parses/modifies the request body, such as `express.json()` or `express.urlencoded()`.
### 📦 Custom Error Handling
By default, the `validate` middleware will send a 400 Bad Request response with a JSON body containing the error message. However, you can provide your own error handling function to customize the error response.```ts
// ... extending the previous exampleconst handler = (errors, req, res, next) => {
res.status(400).json({
message: 'Invalid request data',
errors: errors.map((error) => error.message),
});
};// Use the validate middleware in your route
app.post('/user/:userId', validate({ handler, params, query, body }), (req, res) => {
// Your route logic here
res.send('User data is valid!');
});
```### ⚠️ URL Parameters & Query Strings Coercion
As mentioned in the example above, all URL parameters and query strings are parsed as strings. This means that if you have a URL parameter or query string that is expected to be a number, you must use the `z.coerce.number()` method to coerce the value to a number. This is because Zod will not coerce the value for you, and will instead throw an error if the value is not a string.```ts
const params = {
userId: z.coerce.number(),
};app.get('/user/:userId', validate({ params }), (req, res) => {
// req.params.userId -> number
});
```### ⚠️ Missing Validation Schemas
If you do not provide a validation schema for a particular request component (e.g. `params`, `query`, or `body`), then that component will be assumed to be empty. This means that requests with non-empty components will be rejected, and requests with empty components will be accepted. The types on the `req` object will also reflect this, and will be `undefined` if the component is not provided.```ts
const body = {
name: z.string(),
email: z.string().email(),
};app.post('/user', validate({ body }), (req, res) => {
// req.body.name -> string
// req.body.email -> string
// req.params.age -> undefined
// req.query.age -> undefined
});
```This behaviour is intentional and ensures that you do not try to access or use a property that does not exist on the `req` object.
## ⭐️ Show your support
Give a ⭐️ on GitHub if this project helped you!
## 📝 License
Copyright © [AngaBlue](https://github.com/AngaBlue).
This project is [LGPL--3.0--or--later](https://github.com/AngaBlue/express-zod-safe/blob/master/LICENSE) licensed.