Nuxt3 Best Practices 02: Request Validation
1. Introduction
Nuxt 3 uses Nitro as its server engine, and Nitro adopts the H3 framework. H3 provides convenient methods for easily validating request bodies, query string parameters, and path parameters.
The key validation methods provided by H3 are:
readValidatedBody: Validates request bodies.getValidatedQuery: Validates query string parameters.getValidatedRouterParams: Validates path parameters.
These methods can be used with schema validation libraries such as zod, joi, and myzod. In this article, we will focus on using zod for validation.
Installing zod
First, install zod:
npm install zod
2. Usage Examples
2.1 Validating Request Bodies
When the frontend sends a POST request, we often need to validate the request body data. For example, we may require username to be at least 3 characters long and password to be at least 6 characters long. We can use readValidatedBody to enforce this validation:
import { readValidatedBody } from 'h3';
import z from 'zod';
const userSchema = z.object({
username: z.string().min(3, 'Username must be at least 3 characters long'),
password: z.string().min(6, 'Password must be at least 6 characters long'),
});
export default defineEventHandler(async (event) => {
const body = await readValidatedBody(event, userSchema.parse);
console.log(body);
return {
message: 'Data validation successful!',
};
});
If the request body does not conform to the zod schema, Nuxt will return a 400 Bad Request error.
2.2 Validating Query String Parameters
For GET requests, query parameters are commonly used. Using getValidatedQuery, we can easily validate them. For example, we can define username as an optional string:
import { getValidatedQuery } from 'h3';
import z from 'zod';
const querySchema = z.object({
username: z.string().optional(),
});
export default defineEventHandler(async (event) => {
const query = await getValidatedQuery(event, querySchema.parse);
console.log(query);
return {
message: 'Query parameter validation successful!',
};
});
If username is passed with an invalid type (e.g., an array or number), Nuxt will return a 400 Bad Request error.
2.3 Validating Path Parameters
In RESTful API design, path parameters are often used to identify resources. For example, in a URL like /user/:id, we can use getValidatedRouterParams to ensure that id is a valid UUID:
import { getValidatedRouterParams } from 'h3';
import z from 'zod';
const paramSchema = z.object({
id: z.string().uuid(),
});
export default defineEventHandler(async (event) => {
const params = await getValidatedRouterParams(event, paramSchema.parse);
console.log(params);
return {
message: `User ID ${params.id} validation successful!`,
};
});
If id is not a valid UUID, Nuxt will return a 400 Bad Request error.
3. Conclusion
Nuxt 3, with the help of H3, provides readValidatedBody, getValidatedQuery, and getValidatedRouterParams methods, making server-side validation simple and efficient. By integrating with schema validation libraries like zod, we can ensure that API requests meet the expected data format, preventing invalid data submissions.
By implementing proper validation, we can enhance the security and reliability of our APIs.
I hope this article helps you understand request validation in Nuxt 3! 🎯
Previous article:Nuxt3 Best Practices 01: Logging
Next article:Nuxt3 Best Practices 03: OpenAPI Documentation Output