- Get Started
- Product
- Resources
- Tools & SDKs
- Framework
- Reference
- Get Started
- Product
- Resources
- Tools & SDKs
- Framework
- Reference
3.5.5. Request Body and Query Parameter Validation
In this chapter, you'll learn how to validate request body and query parameters in your custom API route.
Request Validation#
Consider you're creating a POST
API route at /custom
. It accepts two parameters a
and b
that are required numbers, and returns their sum.
Medusa provides two middlewares to validate the request body and query paramters of incoming requests to your custom API routes:
validateAndTransformBody
to validate the request's body parameters against a schema.validateAndTransformQuery
to validate the request's query parameters against a schema.
Both middlewares accept a Zod schema as a parameter, which gives you flexibility in how you define your validation schema with complex rules.
The next steps explain how to add request body and query parameter validation to the API route mentioned earlier.
How to Validate Request Body#
Step 1: Create Validation Schema#
Medusa uses Zod to create validation schemas. These schemas are then used to validate incoming request bodies or query parameters.
To create a validation schema with Zod, create a validators.ts
file in any src/api
subfolder. This file holds Zod schemas for each of your API routes.
For example, create the file src/api/custom/validators.ts
with the following content:
The PostStoreCustomSchema
variable is a Zod schema that indicates the request body is valid if:
- It's an object.
- It has a property
a
that is a required number. - It has a property
b
that is a required number.
Step 2: Add Request Body Validation Middleware#
To use this schema for validating the body parameters of requests to /custom
, use the validateAndTransformBody
middleware provided by @medusajs/framework/http
. It accepts the Zod schema as a parameter.
For example, create the file src/api/middlewares.ts
with the following content:
1import { 2 defineMiddlewares,3 validateAndTransformBody,4} from "@medusajs/framework/http"5import { PostStoreCustomSchema } from "./custom/validators"6 7export default defineMiddlewares({8 routes: [9 {10 matcher: "/custom",11 method: "POST",12 middlewares: [13 validateAndTransformBody(PostStoreCustomSchema),14 ],15 },16 ],17})
This applies the validateAndTransformBody
middleware on POST
requests to /custom
. It uses the PostStoreCustomSchema
as the validation schema.
How the Validation Works
If a request's body parameters don't pass the validation, the validateAndTransformBody
middleware throws an error indicating the validation errors.
If a request's body parameters are validated successfully, the middleware sets the validated body parameters in the validatedBody
property of MedusaRequest
.
Step 3: Use Validated Body in API Route#
In your API route, consume the validated body using the validatedBody
property of MedusaRequest
.
For example, create the file src/api/custom/route.ts
with the following content:
1import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"2import { z } from "zod"3import { PostStoreCustomSchema } from "./validators"4 5type PostStoreCustomSchemaType = z.infer<6 typeof PostStoreCustomSchema7>8 9export const POST = async (10 req: MedusaRequest<PostStoreCustomSchemaType>,11 res: MedusaResponse12) => {13 res.json({14 sum: req.validatedBody.a + req.validatedBody.b,15 })16}
In the API route, you use the validatedBody
property of MedusaRequest
to access the values of the a
and b
properties.
MedusaRequest
, use Zod's infer
type that accepts the type of a schema as a parameter.Test it Out#
To test out the validation, send a POST
request to /custom
passing a
and b
body parameters. You can try sending incorrect request body parameters to test out the validation.
For example, if you omit the a
parameter, you'll receive a 400
response code with the following response data:
How to Validate Request Query Paramters#
The steps to validate the request query parameters are the similar to that of validating the body.
Step 1: Create Validation Schema#
The first step is to create a schema with Zod with the rules of the accepted query parameters.
Consider that the API route accepts two query parameters a
and b
that are numbers, similar to the previous section.
Create the file src/api/custom/validators.ts
with the following content:
1import { z } from "zod"2 3export const PostStoreCustomSchema = z.object({4 a: z.preprocess(5 (val) => {6 if (val && typeof val === "string") {7 return parseInt(val)8 }9 return val10 },11 z12 .number()13 ),14 b: z.preprocess(15 (val) => {16 if (val && typeof val === "string") {17 return parseInt(val)18 }19 return val20 },21 z22 .number()23 ),24})
Since a query parameter's type is originally a string or array of strings, you have to use Zod's preprocess
method to validate other query types, such as numbers.
For both a
and b
, you transform the query parameter's value to an integer first if it's a string, then, you check that the resulting value is a number.
Step 2: Add Request Query Validation Middleware#
Next, you'll use the schema to validate incoming requests' query parameters to the /custom
API route.
Add the validateAndTransformQuery
middleware to the API route in the file src/api/middlewares.ts
:
1import { 2 validateAndTransformQuery,3 defineMiddlewares,4} from "@medusajs/framework/http"5import { PostStoreCustomSchema } from "./custom/validators"6 7export default defineMiddlewares({8 routes: [9 {10 matcher: "/custom",11 method: "POST",12 middlewares: [13 validateAndTransformQuery(14 PostStoreCustomSchema,15 {}16 ),17 ],18 },19 ],20})
The validateAndTransformQuery
accepts two parameters:
- The first one is the Zod schema to validate the query parameters against.
- The second one is an object of options for retrieving data using Query, which you can learn more about in this chapter.
How the Validation Works
If a request's query parameters don't pass the validation, the validateAndTransformQuery
middleware throws an error indicating the validation errors.
If a request's query parameters are validated successfully, the middleware sets the validated query parameters in the validatedQuery
property of MedusaRequest
.
Step 3: Use Validated Query in API Route#
Finally, use the validated query in the API route. The MedusaRequest
parameter has a validatedQuery
parameter that you can use to access the validated parameters.
For example, create the file src/api/custom/route.ts
with the following content:
In the API route, you use the validatedQuery
property of MedusaRequest
to access the values of the a
and b
properties as numbers, then return in the response their sum.
Test it Out#
To test out the validation, send a POST
request to /custom
with a
and b
query parameters. You can try sending incorrect query parameters to see how the validation works.
For example, if you omit the a
parameter, you'll receive a 400
response code with the following response data:
Learn More About Validation Schemas#
To see different examples and learn more about creating a validation schema, refer to Zod's documentation.