|
1
|
--- |
|
2
|
sidebar_label: "use-validated-body-or-query" |
|
3
|
--- |
|
4
|
|
|
5
|
import { Note } from "docs-ui" |
|
6
|
|
|
7
|
export const metadata = { |
|
8
|
title: `use-validated-body-or-query - ESLint plugin rules`, |
|
9
|
} |
|
10
|
|
|
11
|
# {metadata.title} |
|
12
|
|
|
13
|
This rule requires using `req.validatedBody` or `req.validatedQuery` when a validation middleware is applied to the route. |
|
14
|
|
|
15
|
## Severity |
|
16
|
|
|
17
|
`warn`. This rule is enabled in the [strict](../../page.mdx#strict) preset. |
|
18
|
|
|
19
|
By default, Medusa projects use the [recommended](../../page.mdx#recommended) preset, which doesn't enable this rule. To use it, switch to the [strict](../../page.mdx#strict) preset. |
|
20
|
|
|
21
|
## What it Targets |
|
22
|
|
|
23
|
This rule targets `route.ts` and `route.js` files in your project's `src/api` directory. It reports access to `req.body` or `req.query` in a handler when a `validateAndTransformBody` or `validateAndTransformQuery` middleware is applied to the route. |
|
24
|
|
|
25
|
The following code is reported by the rule when body validation is applied to the route: |
|
26
|
|
|
27
|
```ts title="src/api/admin/customers/route.ts" |
|
28
|
export const POST = async (req, res) => { |
|
29
|
res.json(req.body) |
|
30
|
} |
|
31
|
``` |
|
32
|
|
|
33
|
Instead, use the validated property: |
|
34
|
|
|
35
|
```ts title="src/api/admin/customers/route.ts" |
|
36
|
export const POST = async (req, res) => { |
|
37
|
res.json(req.validatedBody) |
|
38
|
} |
|
39
|
``` |
|
40
|
|
|
41
|
## Why it's Important |
|
42
|
|
|
43
|
A validation middleware populates `req.validatedBody` and `req.validatedQuery` with the parsed and transformed data. Reading the raw `req.body` or `req.query` skips that validation and transformation. |
|
44
|
|
|
45
|
Learn more in the [Validation documentation](!docs!/learn/fundamentals/api-routes/validation). |
|
46
|
|
|
47
|
## Fixable |
|
48
|
|
|
49
|
This rule is auto-fixable. Run the linter with the `--fix` option to apply the fix automatically. |
|
50
|
|
|
51
|
## Turn it Off |
|
52
|
|
|
53
|
To turn off this rule, set it to `off` in your ESLint configuration: |
|
54
|
|
|
55
|
```ts title="eslint.config.ts" |
|
56
|
import { defineConfig } from "eslint/config" |
|
57
|
import medusa from "@medusajs/eslint-plugin" |
|
58
|
|
|
59
|
export default defineConfig([ |
|
60
|
...medusa.configs.strict, |
|
61
|
{ |
|
62
|
rules: { |
|
63
|
"@medusajs/use-validated-body-or-query": "off", |
|
64
|
}, |
|
65
|
}, |
|
66
|
]) |
|
67
|
``` |
|
68
|
|
|
69
|
Or disable it for a single line using an inline comment: |
|
70
|
|
|
71
|
```ts |
|
72
|
// eslint-disable-next-line @medusajs/use-validated-body-or-query |
|
73
|
res.json(req.body) |
|
74
|
``` |