Validation
The client automatically validates request parameters, query strings, and request bodies using Zod schemas.
Automatic Validation
When you make a request, the client automatically validates:
- Path parameters - Validated against the
paramsschema - Query parameters - Validated against the
queryschema - Request body - Validated against the
bodyschema - Response data - Validated against the
outputschema
const result = await client.post("/users", {
body: {
name: "Alice",
email: "invalid-email", // ❌ This will throw ValidationError
},
});
Validation Errors
If validation fails, the client throws a ValidationError:
import { ValidationError } from "@alt-stack/http-client-fetch";
try {
await client.get("/users/{id}", {
params: { id: 123 }, // ❌ Should be string
});
} catch (error) {
if (error instanceof ValidationError) {
console.error("Validation failed:", error.message);
console.error("Validation errors:", error.validationErrors);
}
}
The ValidationError includes:
message: Human-readable error messagevalidationErrors: Validation error details from Zodendpoint: The endpoint that failed validationmethod: The HTTP method that failed validation
Type Safety
TypeScript ensures you pass the correct types at compile time:
// ✅ TypeScript knows this is correct
await client.get("/users/{id}", {
params: { id: "123" },
});
// ❌ TypeScript error - id must be string
await client.get("/users/{id}", {
params: { id: 123 },
});
Response Validation
Response data is automatically validated when received:
const result = await client.get("/users/{id}", {
params: { id: "123" },
});
if (result.success) {
// result.body is validated and typed
console.log(result.body.name); // ✅ Type-safe
}
If the response doesn't match the expected schema, an error is returned in the result.