Validation

Nuxt Server Utils provides a simple way to validate incoming requests. It provides a instance of Validator class that can be used to validate incoming requests against a zod schema.

Validating incoming requests

The Validator.validate method is used to validate incoming requests. It accepts the event object and a zod schema. If the request is valid, the request is allowed to proceed. If the request is invalid, the request is rejected with a 400 Bad Request error.

server/api/users.post.ts
import { Validator } from "#nuxt-server-utils";

export default defineEventHandler(async (event) => {
  const schema = z.object({
    name: z.string().min(3).max(255),
    email: z.string().email(),
    password: z.string().min(8).max(255),
  });

  const body = await readBody(event);

  Validator.validateSchema(schema, body);

  // ...
});