4.1.3. Middlewares

In this chapter, you’ll learn about middlewares and how to create them.

What is a Middleware?#

A middleware is a function executed when a request is sent to an API Route. It's executed before the route handler function.


How to Create a Middleware?#

Middlewares are defined in the special file src/api/middlewares.ts. The file must export an object of middleware configurations.

For example:

src/api/middlewares.ts
1import type { 2  MedusaNextFunction, 3  MedusaRequest, 4  MedusaResponse, 5  MiddlewaresConfig,6} from "@medusajs/medusa"7
8export const config: MiddlewaresConfig = {9  routes: [10    {11      matcher: "/store*",12      middlewares: [13        (14          req: MedusaRequest, 15          res: MedusaResponse, 16          next: MedusaNextFunction17        ) => {18          console.log("Received a request!")19
20          next()21        },22      ],23    },24  ],25}

The middleware configurations object has the property routes. Its value is an array of middleware route objects, each having the following properties:

  • matcher: a string or regular expression indicating the API route path to apply the middleware on.
  • middlewares: An array of middleware functions.

In the example above, you define a middleware that logs the message Received a request! whenever a request is sent to an API route path starting with /store.


Test the Middleware#

To test the middleware:

  1. Start the application:
  1. Send a request to any API route starting with /store.
  2. See the following message in the terminal:
Received a request!

When to Use Middlewares#

Use middlewares when
  • You want to protect API routes by a custom condition.
  • You're modifying the request body.

Middleware Function Parameters#

The middleware function accepts three parameters:

  1. A request object of type MedusaRequest.
  2. A response object of type MedusaResponse.
  3. A function of type MedusaNextFunction that executes the next middleware in the stack.
Important

You must call the next function in the middleware. Otherwise, other middlewares and the API route handler won’t execute.


Restrict HTTP Methods#

In addition to the matcher configuration, you can restrict which HTTP methods the middleware is applied to.

For example:

src/api/middlewares.ts
6} from "@medusajs/medusa"7
8export const config: MiddlewaresConfig = {9  routes: [10    {11      matcher: "/store*",12      method: ["POST", "PUT"],13      middlewares: [14        (15          req: MedusaRequest, 16          res: MedusaResponse, 17          next: MedusaNextFunction18        ) => {19          console.log("Received a request!")20
21          next()22        },23      ],24    },25  ],26}

The object in the routes array accepts the property method whose value is one or more HTTP methods to apply the middleware to.

This applies the middleware only when a POST or PUT request is sent to an API route path starting with /store.

Was this chapter helpful?