Scaling Product APIs with Zod and Express
Improving Data Integrity in Ecommerce APIs
In the ecommerce-fullstack project, managing product data requires a robust approach to handling both public access and administrative updates. Relying on loose request handling often leads to runtime errors or invalid data in the database. By integrating Zod for schema validation within our Express middleware, we have moved toward a type-safe, predictable API layer.
Defining Schemas with Zod
Instead of manual checks, we define the expected shape of our product data upfront. This allows for centralized validation logic that is shared between public read operations and administrative update tasks.
import { z } from 'zod';
const productSchema = z.object({
name: z.string().min(1),
price: z.number().positive(),
stock: z.number().int().nonnegative(),
});
Implementing Validation Middleware
We utilize the middleware pattern to ensure that the request body adheres to our schema before it ever hits the main business logic. This drastically reduces the surface area for bugs.
import { Request, Response, NextFunction } from 'express';
export const validateProduct = (schema: z.ZodSchema) =>
(req: Request, res: Response, next: NextFunction) => {
const result = schema.safeParse(req.body);
if (!result.success) {
return res.status(400).json({ errors: result.error.issues });
}
next();
};
Applying to Routes
With the middleware defined, securing our update endpoints becomes a declarative task. We can now easily differentiate between the data needed for a public product view and the stricter requirements for administrative modifications.
app.put('/admin/products/:id', validateProduct(productSchema), (req, res) => {
// Logic for updating the product safely
res.sendStatus(200);
});
Results
By formalizing our request validation, we have eliminated a common class of "bad data" errors during product updates. The code is more readable, and the validation logic is now highly reusable across different API surfaces.
Next Steps
Moving forward, consider adding custom refinement rules to the Zod schemas if you need to validate complex business constraints, such as comparing stock levels against existing inventory records during the update process.
Generated with Gitvlg.com