Skip to content

Instantly share code, notes, and snippets.

@KolbySisk
Last active August 29, 2022 14:31
Show Gist options
  • Save KolbySisk/a71564a8b340067a59b82842d1c0f92f to your computer and use it in GitHub Desktop.
Save KolbySisk/a71564a8b340067a59b82842d1c0f92f to your computer and use it in GitHub Desktop.
import * as z from 'zod';
import { Middleware } from 'next-api-route-middleware';
export const validateBody = (zodSchema: z.ZodSchema): Middleware => {
return async function (req, res, next) {
const body = typeof req.body === 'object' ? req.body : JSON.parse(req.body);
const validation = zodSchema.safeParse(body);
if (!validation.success) {
return res.status(400).send({
message: validation.error,
});
}
next();
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment