5.2.5. Request Body Parameter Validation

In this chapter, you'll learn how to validate request body parameters in your custom API route.

Example Scenario#

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.

The next steps explain how to add validation to this API route, as an example.


Step 1: Create Zod Schema#

Medusa uses Zod to validate the body parameters of an incoming request.

To use Zod to validate your custom schemas, 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:

src/api/custom/validators.ts
1import { z } from "zod"2
3export const PostStoreCustomSchema = z.object({4  a: z.number(),5  b: z.number(),6})

The PostStoreCustomSchema variable is a Zod schema that indicates the request body is valid if:

  1. It's an object.
  2. It has a property a that is a required number.
  3. It has a property b that is a required number.

Step 2: Add Validation Middleware#

To use this schema for validating the body parameters of requests to /custom, use the validateAndTransformBody middleware provided by @medusajs/framework/utils. It accepts the Zod schema as a parameter.

For example, create the file src/api/middlewares.ts with the following content:

src/api/middlewares.ts
1import { defineMiddlewares } from "@medusajs/medusa"2import { 3  validateAndTransformBody,4} from "@medusajs/framework/utils"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:

src/api/custom/route.ts
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.

TipTo pass the request body's type as a type parameter to 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. You can try sending incorrect request body parameters.

For example, if you omit the a parameter, you'll receive a 400 response code with the following response data:

Code
1{2  "type": "invalid_data",3  "message": "Invalid request: Field 'a' is required"4}

Learn More About Validation Schemas#

To see different examples and learn more about creating a validation schema, refer to Zod's documentation.

Was this chapter helpful?
Edit this page