|
1
|
export const metadata = { |
|
2
|
title: `${pageNumber} Request Body and Query Parameter Validation`, |
|
3
|
} |
|
4
|
|
|
5
|
# {metadata.title} |
|
6
|
|
|
7
|
In this chapter, you'll learn how to validate request body and query parameters in your custom API route. |
|
8
|
|
|
9
|
## Request Validation |
|
10
|
|
|
11
|
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. |
|
12
|
|
|
13
|
Medusa provides two middlewares to validate the request body and query parameters of incoming requests to your custom API routes: |
|
14
|
|
|
15
|
- `validateAndTransformBody` to validate the request's body parameters against a schema. |
|
16
|
- `validateAndTransformQuery` to validate the request's query parameters against a schema. |
|
17
|
|
|
18
|
Both middlewares accept a [Zod](https://zod.dev/) schema as a parameter, which gives you flexibility in how you define your validation schema with complex rules. |
|
19
|
|
|
20
|
The next steps explain how to add request body and query parameter validation to the API route mentioned earlier. |
|
21
|
|
|
22
|
--- |
|
23
|
|
|
24
|
## How to Validate Request Body |
|
25
|
|
|
26
|
### Step 1: Create Validation Schema |
|
27
|
|
|
28
|
Medusa uses [Zod](https://zod.dev/) to create validation schemas. These schemas are then used to validate incoming request bodies or query parameters. |
|
29
|
|
|
30
|
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. |
|
31
|
|
|
32
|
For example, create the file `src/api/custom/validators.ts` with the following content: |
|
33
|
|
|
34
|
<Note> |
|
35
|
|
|
36
|
As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`. |
|
37
|
|
|
38
|
</Note> |
|
39
|
|
|
40
|
```ts title="src/api/custom/validators.ts" |
|
41
|
import { z } from "@medusajs/framework/zod" |
|
42
|
|
|
43
|
export const PostStoreCustomSchema = z.object({ |
|
44
|
a: z.number(), |
|
45
|
b: z.number(), |
|
46
|
}) |
|
47
|
``` |
|
48
|
|
|
49
|
The `PostStoreCustomSchema` variable is a Zod schema that indicates the request body is valid if: |
|
50
|
|
|
51
|
1. It's an object. |
|
52
|
2. It has a property `a` that is a required number. |
|
53
|
3. It has a property `b` that is a required number. |
|
54
|
|
|
55
|
### Step 2: Add Request Body Validation Middleware |
|
56
|
|
|
57
|
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. |
|
58
|
|
|
59
|
For example, create the file `src/api/middlewares.ts` with the following content: |
|
60
|
|
|
61
|
```ts title="src/api/middlewares.ts" |
|
62
|
import { |
|
63
|
defineMiddlewares, |
|
64
|
validateAndTransformBody, |
|
65
|
} from "@medusajs/framework/http" |
|
66
|
import { PostStoreCustomSchema } from "./custom/validators" |
|
67
|
|
|
68
|
export default defineMiddlewares({ |
|
69
|
routes: [ |
|
70
|
{ |
|
71
|
matcher: "/custom", |
|
72
|
method: "POST", |
|
73
|
middlewares: [ |
|
74
|
validateAndTransformBody(PostStoreCustomSchema), |
|
75
|
], |
|
76
|
}, |
|
77
|
], |
|
78
|
}) |
|
79
|
``` |
|
80
|
|
|
81
|
This applies the `validateAndTransformBody` middleware on `POST` requests to `/custom`. It uses the `PostStoreCustomSchema` as the validation schema. |
|
82
|
|
|
83
|
#### How the Validation Works |
|
84
|
|
|
85
|
If a request's body parameters don't pass the validation, the `validateAndTransformBody` middleware throws an error indicating the validation errors. |
|
86
|
|
|
87
|
If a request's body parameters are validated successfully, the middleware sets the validated body parameters in the `validatedBody` property of `MedusaRequest`. |
|
88
|
|
|
89
|
### Step 3: Use Validated Body in API Route |
|
90
|
|
|
91
|
In your API route, consume the validated body using the `validatedBody` property of `MedusaRequest`. |
|
92
|
|
|
93
|
For example, create the file `src/api/custom/route.ts` with the following content: |
|
94
|
|
|
95
|
export const routeHighlights = [ |
|
96
|
["5", "PostStoreCustomSchemaType", "Infer the request body type from the schema to pass it as a type parameter to `MedusaRequest`."], |
|
97
|
["14", "", "Access the body parameters using `validatedBody`."] |
|
98
|
] |
|
99
|
|
|
100
|
```ts title="src/api/custom/route.ts" highlights={routeHighlights} |
|
101
|
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http" |
|
102
|
import { z } from "@medusajs/framework/zod" |
|
103
|
import { PostStoreCustomSchema } from "./validators" |
|
104
|
|
|
105
|
type PostStoreCustomSchemaType = z.infer< |
|
106
|
typeof PostStoreCustomSchema |
|
107
|
> |
|
108
|
|
|
109
|
export const POST = async ( |
|
110
|
req: MedusaRequest<PostStoreCustomSchemaType>, |
|
111
|
res: MedusaResponse |
|
112
|
) => { |
|
113
|
res.json({ |
|
114
|
sum: req.validatedBody.a + req.validatedBody.b, |
|
115
|
}) |
|
116
|
} |
|
117
|
``` |
|
118
|
|
|
119
|
In the API route, you use the `validatedBody` property of `MedusaRequest` to access the values of the `a` and `b` properties. |
|
120
|
|
|
121
|
<Note title="Tip"> |
|
122
|
|
|
123
|
To 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. |
|
124
|
|
|
125
|
</Note> |
|
126
|
|
|
127
|
### Test it Out |
|
128
|
|
|
129
|
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. |
|
130
|
|
|
131
|
For example, if you omit the `a` parameter, you'll receive a `400` response code with the following response data: |
|
132
|
|
|
133
|
```json |
|
134
|
{ |
|
135
|
"type": "invalid_data", |
|
136
|
"message": "Invalid request: Field 'a' is required" |
|
137
|
} |
|
138
|
``` |
|
139
|
|
|
140
|
--- |
|
141
|
|
|
142
|
## How to Validate Request Query Parameters |
|
143
|
|
|
144
|
The steps to validate the request query parameters are the similar to that of [validating the body](#how-to-validate-request-body). |
|
145
|
|
|
146
|
### Step 1: Create Validation Schema |
|
147
|
|
|
148
|
The first step is to create a schema with Zod with the rules of the accepted query parameters. |
|
149
|
|
|
150
|
Consider that the API route accepts two query parameters `a` and `b` that are numbers, similar to the previous section. |
|
151
|
|
|
152
|
Create the file `src/api/custom/validators.ts` with the following content: |
|
153
|
|
|
154
|
```ts title="src/api/custom/validators.ts" |
|
155
|
import { z } from "@medusajs/framework/zod" |
|
156
|
|
|
157
|
export const PostStoreCustomSchema = z.object({ |
|
158
|
a: z.preprocess( |
|
159
|
(val) => { |
|
160
|
if (val && typeof val === "string") { |
|
161
|
return parseInt(val) |
|
162
|
} |
|
163
|
return val |
|
164
|
}, |
|
165
|
z |
|
166
|
.number() |
|
167
|
), |
|
168
|
b: z.preprocess( |
|
169
|
(val) => { |
|
170
|
if (val && typeof val === "string") { |
|
171
|
return parseInt(val) |
|
172
|
} |
|
173
|
return val |
|
174
|
}, |
|
175
|
z |
|
176
|
.number() |
|
177
|
), |
|
178
|
}) |
|
179
|
``` |
|
180
|
|
|
181
|
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. |
|
182
|
|
|
183
|
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. |
|
184
|
|
|
185
|
### Step 2: Add Request Query Validation Middleware |
|
186
|
|
|
187
|
Next, you'll use the schema to validate incoming requests' query parameters to the `/custom` API route. |
|
188
|
|
|
189
|
Add the `validateAndTransformQuery` middleware to the API route in the file `src/api/middlewares.ts`: |
|
190
|
|
|
191
|
```ts title="src/api/middlewares.ts" |
|
192
|
import { |
|
193
|
validateAndTransformQuery, |
|
194
|
defineMiddlewares, |
|
195
|
} from "@medusajs/framework/http" |
|
196
|
import { PostStoreCustomSchema } from "./custom/validators" |
|
197
|
|
|
198
|
export default defineMiddlewares({ |
|
199
|
routes: [ |
|
200
|
{ |
|
201
|
matcher: "/custom", |
|
202
|
method: "POST", |
|
203
|
middlewares: [ |
|
204
|
validateAndTransformQuery( |
|
205
|
PostStoreCustomSchema, |
|
206
|
{} |
|
207
|
), |
|
208
|
], |
|
209
|
}, |
|
210
|
], |
|
211
|
}) |
|
212
|
``` |
|
213
|
|
|
214
|
The `validateAndTransformQuery` accepts two parameters: |
|
215
|
|
|
216
|
- The first one is the Zod schema to validate the query parameters against. |
|
217
|
- The second one is an object of options for retrieving data using Query, which you can learn more about in [this chapter](../../../fundamentals/query/page.mdx). |
|
218
|
|
|
219
|
#### How the Validation Works |
|
220
|
|
|
221
|
If a request's query parameters don't pass the validation, the `validateAndTransformQuery` middleware throws an error indicating the validation errors. |
|
222
|
|
|
223
|
If a request's query parameters are validated successfully, the middleware sets the validated query parameters in the `validatedQuery` property of `MedusaRequest`. |
|
224
|
|
|
225
|
### Step 3: Use Validated Query in API Route |
|
226
|
|
|
227
|
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. |
|
228
|
|
|
229
|
For example, create the file `src/api/custom/route.ts` with the following content: |
|
230
|
|
|
231
|
```ts title="src/api/custom/route.ts" |
|
232
|
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http" |
|
233
|
|
|
234
|
export const GET = async ( |
|
235
|
req: MedusaRequest, |
|
236
|
res: MedusaResponse |
|
237
|
) => { |
|
238
|
const a = req.validatedQuery.a as number |
|
239
|
const b = req.validatedQuery.b as number |
|
240
|
|
|
241
|
res.json({ |
|
242
|
sum: a + b, |
|
243
|
}) |
|
244
|
} |
|
245
|
``` |
|
246
|
|
|
247
|
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. |
|
248
|
|
|
249
|
### Test it Out |
|
250
|
|
|
251
|
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. |
|
252
|
|
|
253
|
For example, if you omit the `a` parameter, you'll receive a `400` response code with the following response data: |
|
254
|
|
|
255
|
```json |
|
256
|
{ |
|
257
|
"type": "invalid_data", |
|
258
|
"message": "Invalid request: Field 'a' is required" |
|
259
|
} |
|
260
|
``` |
|
261
|
|
|
262
|
--- |
|
263
|
|
|
264
|
## Learn More About Validation Schemas |
|
265
|
|
|
266
|
To see different examples and learn more about creating a validation schema, refer to [Zod's documentation](https://zod.dev). |