Raw
1 export const metadata = {
2 title: `${pageNumber} Configure Request Body Parser`,
3 }
4
5 # {metadata.title}
6
7 In this chapter, you'll learn how to configure the request body parser for your API routes.
8
9 ## Default Body Parser Configuration
10
11 The Medusa application configures the body parser by default to parse JSON, URL-encoded, and text request content types. You can parse other data types by adding the relevant [Express middleware](https://expressjs.com/en/guide/using-middleware.html), or preserve the raw body data by configuring the body parser, which is useful for webhook requests.
12
13 This chapter provides examples of configuring the body parser for different data types or use cases.
14
15 ---
16
17 ## Preserve Raw Body Data for Webhooks
18
19 If your API route receives webhook requests, you might want to preserve the raw body data. To do this, you can configure the body parser to parse the raw body data and store it in the `req.rawBody` property.
20
21 To do this, create the file `src/api/middlewares.ts` with the following content:
22
23 export const preserveHighlights = [
24 ["7", "preserveRawBody", "Enable preserving the raw body data."],
25 ]
26
27 ```ts title="src/api/middlewares.ts" highlights={preserveHighlights}
28 import { defineMiddlewares } from "@medusajs/framework/http"
29
30 export default defineMiddlewares({
31 routes: [
32 {
33 method: ["POST"],
34 bodyParser: { preserveRawBody: true },
35 matcher: "/custom",
36 },
37 ],
38 })
39 ```
40
41 The middleware route object passed to `routes` accepts a `bodyParser` property, whose value is a configuration object for the default body parser. By enabling the `preserveRawBody` property, the raw body data is preserved and stored in the `req.rawBody` property.
42
43 <Note title="Tip">
44
45 Learn more about [middlewares](../middlewares/page.mdx).
46
47 </Note>
48
49 You can then access the raw body data in your API route handler:
50
51 ```ts title="src/api/custom/route.ts"
52 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
53
54 export async function POST(
55 req: MedusaRequest,
56 res: MedusaResponse
57 ) {
58 console.log(req.rawBody)
59
60 // TODO use raw body
61 }
62 ```
63
64 <Note title="Important">
65
66 The default body parser only parses JSON, URL-encoded, and text content types, so `preserveRawBody` only populates `req.rawBody` when the request's `Content-Type` header is set to one of those types. If your route receives a request with another content type, such as a webhook whose provider doesn't document its `Content-Type` header, use the [Express middleware](https://expressjs.com/en/guide/using-middleware.html) approach mentioned earlier in this chapter to read the raw request stream yourself.
67
68 </Note>
69
70 ---
71
72 ## Disable the Default Body Parser
73
74 You can disable the default body parser for a route by setting its `bodyParser` property to `false`. This is useful if you want to parse the request body yourself, for example, using custom [Express middleware](https://expressjs.com/en/guide/using-middleware.html).
75
76 When `bodyParser` is set to `false`, the Medusa application skips its JSON, URL-encoded, and text parsers for that route, and `req.rawBody` isn't set. Use this option instead of `preserveRawBody` when you need full control over how the request body is read, rather than only preserving the raw body alongside the parsed one.
77
78 For example:
79
80 ```ts title="src/api/middlewares.ts"
81 import { defineMiddlewares } from "@medusajs/framework/http"
82
83 function readRawBody(req, res, next) {
84 const chunks: Buffer[] = []
85
86 req.on("data", (chunk) => chunks.push(chunk))
87 req.on("end", () => {
88 req.rawBody = Buffer.concat(chunks)
89 next()
90 })
91 }
92
93 export default defineMiddlewares({
94 routes: [
95 {
96 method: ["POST"],
97 bodyParser: false,
98 matcher: "/custom",
99 middlewares: [readRawBody],
100 },
101 ],
102 })
103 ```
104
105 In the example above, the custom `readRawBody` middleware reads the raw request stream regardless of its content type, then stores it in `req.rawBody` for the route handler to use.
106
107 You can then access the raw body data in your API route handler:
108
109 ```ts title="src/api/custom/route.ts"
110 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
111
112 export async function POST(
113 req: MedusaRequest,
114 res: MedusaResponse
115 ) {
116 console.log(req.rawBody)
117
118 // TODO use raw body
119 }
120 ```
121
122 ---
123
124 ## Configure Request Body Size Limit
125
126 By default, the body parser limits the request body size to `100kb`. If a request body exceeds that size, the Medusa application throws an error.
127
128 You can configure the body parser to accept larger request bodies by setting the `sizeLimit` property of the `bodyParser` object in a middleware route object. For example:
129
130 export const sizeLimitHighlights = [
131 ["7", "sizeLimit", "Set the request body size limit."],
132 ]
133
134 ```ts title="src/api/middlewares.ts" highlights={sizeLimitHighlights}
135 import { defineMiddlewares } from "@medusajs/framework/http"
136
137 export default defineMiddlewares({
138 routes: [
139 {
140 method: ["POST"],
141 bodyParser: { sizeLimit: "2mb" },
142 matcher: "/custom",
143 },
144 ],
145 })
146 ```
147
148 The `sizeLimit` property accepts one of the following types of values:
149
150 - A string representing the size limit (for example, `100kb`, `2mb`, `5gb`). It is passed to the [bytes](https://www.npmjs.com/package/bytes) library to parse the size.
151 - A number representing the size limit in bytes. For example, `1024` for 1kb.
152
153 ### Overriding Request Body Size Limit
154
155 You can't override the request body size limit for existing routes, such as Medusa's Store and Admin API routes, due to how [middlewares are applied](../middlewares/page.mdx#how-are-middlewares-ordered-and-applied).
156
157 If you need to override the request body size limit for a specific route, you can create a custom [API route](../page.mdx) that executes the same functionality as the original route, but with the body size limit you need.
158
159 Learn more in the [Override API Routes](../override/page.mdx) chapter.
160
161 ---
162
163 ## Configure File Uploads
164
165 To accept file uploads in your API routes, you can configure the [Express Multer middleware](https://expressjs.com/en/resources/middleware/multer.html) on your route.
166
167 The `multer` package is available through the `@medusajs/medusa` package, so you don't need to install it. However, for better TypeScript support, install the `@types/multer` package as a development dependency:
168
169 ```bash npm2yarn
170 npm install --save-dev @types/multer
171 ```
172
173 Then, to configure file uploads for your route, create the file `src/api/middlewares.ts` with the following content:
174
175 export const uploadHighlights = [
176 ["4", "upload", "Configure the upload middleware."],
177 ["13", "upload", "Add the upload middleware to the route."],
178 ["13", `"files"`, "Specify the field name for the uploaded files."]
179 ]
180
181 ```ts title="src/api/middlewares.ts" highlights={uploadHighlights}
182 import { defineMiddlewares } from "@medusajs/framework/http"
183 import multer from "multer"
184
185 const upload = multer({ storage: multer.memoryStorage() })
186
187 export default defineMiddlewares({
188 routes: [
189 {
190 method: ["POST"],
191 matcher: "/custom",
192 middlewares: [
193 // @ts-ignore
194 upload.array("files"),
195 ],
196 },
197 ],
198 })
199 ```
200
201 In the example above, you configure the `multer` middleware to store the uploaded files in memory.
202
203 Then, you apply the `upload.array("files")` middleware to the route to accept file uploads. By using the `array` method, you accept multiple file uploads with the same `files` field name.
204
205 You can then access the uploaded files in your API route handler:
206
207 ```ts title="src/api/custom/route.ts"
208 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
209 import { MedusaError } from "@medusajs/framework/utils"
210 import { uploadFilesWorkflow } from "@medusajs/medusa/core-flows"
211
212 export async function POST(
213 req: MedusaRequest,
214 res: MedusaResponse
215 ) {
216 const files = req.files as Express.Multer.File[]
217
218 if (!files?.length) {
219 throw new MedusaError(
220 MedusaError.Types.INVALID_DATA,
221 "No files were uploaded"
222 )
223 }
224
225 const { result } = await uploadFilesWorkflow(req.scope).run({
226 input: {
227 files: files?.map((f) => ({
228 filename: f.originalname,
229 mimeType: f.mimetype,
230 content: f.buffer.toString("base64"),
231 access: "public",
232 })),
233 },
234 })
235
236 res.status(200).json({ files: result })
237 }
238 ```
239
240 The uploaded files are stored in the `req.files` property as an array of Multer file objects that have properties like `filename` and `mimetype`.
241
242 <Note>
243
244 Always encode the file content as `base64` when passing it to `uploadFilesWorkflow`. The File Module Providers expect base64-encoded content, and using `binary` encoding will corrupt binary files such as images when stored by remote providers.
245
246 </Note>
247
248 To upload the files, you can use the [uploadFilesWorkflow](!resources!/references/medusa-workflows/uploadFilesWorkflow), which uploads the files using the configured [File Module Provider](!resources!/infrastructure-modules/file).
249
250 ### Test API Route
251
252 To test the API route, send a `POST` request to the `/custom` endpoint with the `files` field containing one or more files:
253
254 ```bash
255 curl -X POST 'localhost:9000/custom' \
256 --form 'files=@"/path/to/file.png"'
257 ```
258
259 Where `/path/to/file.png` is the path to the file you want to upload.
260
261 The request will return a JSON response with the uploaded file information:
262
263 ```json title="Example Response"
264 {
265 "files": [
266 {
267 "id": "file_1",
268 "url": "https://example.com/files/file_1"
269 }
270 ]
271 }
272 ```