3.6.5. Configure Request Body Parser
In this chapter, you'll learn how to configure the request body parser for your API routes.
Default Body Parser Configuration#
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, or preserve the raw body data by configuring the body parser, which is useful for webhook requests.
This chapter provides examples of configuring the body parser for different data types or use cases.
Preserve Raw Body Data for Webhooks#
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.
To do this, create the file src/api/middlewares.ts
with the following content:
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.
You can then access the raw body data in your API route handler:
Configure Request Body Size Limit#
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.
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:
The sizeLimit
property accepts one of the following types of values:
- A string representing the size limit (for example,
100kb
,2mb
,5gb
). It is passed to the bytes library to parse the size. - A number representing the size limit in bytes. For example,
1024
for 1kb.
Overriding Request Body Size Limit#
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.
If you need to override the request body size limit for a specific route, you can create a custom API route that executes the same functionality as the original route, but with the body size limit you need.
Learn more in the Override API Routes chapter.
Configure File Uploads#
To accept file uploads in your API routes, you can configure the Express Multer middleware on your route.
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:
Then, to configure file uploads for your route, create the file src/api/middlewares.ts
with the following content:
1import { defineMiddlewares } from "@medusajs/framework/http"2import multer from "multer"3 4const upload = multer({ storage: multer.memoryStorage() })5 6export default defineMiddlewares({7 routes: [8 {9 method: ["POST"],10 matcher: "/custom",11 middlewares: [12 // @ts-ignore13 upload.array("files"),14 ],15 },16 ],17})
In the example above, you configure the multer
middleware to store the uploaded files in memory.
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.
You can then access the uploaded files in your API route handler:
1import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"2import { MedusaError } from "@medusajs/framework/utils"3import { uploadFilesWorkflow } from "@medusajs/medusa/core-flows"4 5export async function POST(6 req: MedusaRequest,7 res: MedusaResponse8) {9 const files = req.files as Express.Multer.File[]10 11 if (!files?.length) {12 throw new MedusaError(13 MedusaError.Types.INVALID_DATA,14 "No files were uploaded"15 )16 }17 18 const { result } = await uploadFilesWorkflow(req.scope).run({19 input: {20 files: files?.map((f) => ({21 filename: f.originalname,22 mimeType: f.mimetype,23 content: f.buffer.toString("binary"),24 access: "public",25 })),26 },27 })28 29 res.status(200).json({ files: result })30}
The uploaded files are stored in the req.files
property as an array of Multer file objects that have properties like filename
and mimetype
.
To upload the files, you can use the uploadFilesWorkflow, which uploads the files using the configured File Module Provider.
Test API Route#
To test the API route, send a POST
request to the /custom
endpoint with the files
field containing one or more files:
Where /path/to/file.png
is the path to the file you want to upload.
The request will return a JSON response with the uploaded file information: