Skip to main content

How to Add a Middleware

In this document, you’ll learn how to add a middleware to an existing or custom route in Medusa.

Overview

As the Medusa server is built on top of Express, Express’s features can be utilized during your development with Medusa.

One feature in particular is adding a middleware. A middleware is a function that has access to the request and response objects.

A middleware can be used to perform an action when an endpoint is called or modify the response, among other usages.

You can add a middleware to an existing route in the Medusa server, a route in a plugin, or your custom routes.


Add a Middleware

Adding a middleware is very similar to adding a custom endpoint. The middleware must be created either in the src/api/index.ts entry point, or other TypeScript or JavaScript files imported into src/api/index.ts.

Learn more about creating custom endpoints in this documentation.

The following code snippet is an example of adding a middleware:

src/api/index.ts
import { Router } from "express"

export default () => {
const router = Router()

router.use("/store/products", (req, res, next) => {
// / perform an action when retrieving products
next()
})

return router
}
Report Incorrect CodeReport Incorrect CodeCopy to ClipboardCopy to Clipboard

This code snippet adds a middleware to the List Products endpoint. In the middleware function, you can perform any action.

Then, you must call the next method received as a third parameter in the middleware function to ensure that the endpoint executes after the middleware.

You can learn more about Middlewares and their capabilities in Express’s documentation.


Building Files

Similar to custom endpoints, you must transpile the files under src into the dist directory for the server to load them.

To do that, run the following command before running the Medusa server:

npm run build
Report Incorrect CodeReport Incorrect CodeCopy to ClipboardCopy to Clipboard

See Also