* initialized next.js project * finished markdown sections * added operation schema component * change page metadata * eslint fixes * fixes related to deployment * added response schema * resolve max stack issue * support for different property types * added support for property types * added loading for components * added more loading * type fixes * added oneOf type * removed console * fix replace with push * refactored everything * use static content for description * fixes and improvements * added code examples section * fix path name * optimizations * fixed tag navigation * add support for admin and store references * general enhancements * optimizations and fixes * fixes and enhancements * added search bar * loading enhancements * added loading * added code blocks * added margin top * add empty response text * fixed oneOf parameters * added path and query parameters * general fixes * added base path env variable * small fix for arrays * enhancements * design enhancements * general enhancements * fix isRequired * added enum values * enhancements * general fixes * general fixes * changed oas generation script * additions to the introduction section * added copy button for code + other enhancements * fix response code block * fix metadata * formatted store introduction * move sidebar logic to Tags component * added test env variables * fix code block bug * added loading animation * added expand param + loading * enhance operation loading * made responsive + improvements * added loading provider * fixed loading * adjustments for small devices * added sidebar label for endpoints * added feedback component * fixed analytics * general fixes * listen to scroll for other headings * added sample env file * update api ref files + support new fields * fix for external docs link * added new sections * fix last item in sidebar not showing * move docs content to www/docs * change redirect url * revert change * resolve build errors * configure rewrites * changed to environment variable url * revert changing environment variable name * add environment variable for API path * fix links * fix tailwind settings * remove vercel file * reconfigured api route * move api page under api * fix page metadata * fix external link in navigation bar * update api spec * updated api specs * fixed google lint error * add max-height on request samples * add padding before loading * fix for one of name * fix undefined types * general fixes * remove response schema example * redesigned navigation bar * redesigned sidebar * fixed up paddings * added feedback component + report issue * fixed up typography, padding, and general styling * redesigned code blocks * optimization * added error timeout * fixes * added indexing with algolia + fixes * fix errors with algolia script * redesign operation sections * fix heading scroll * design fixes * fix padding * fix padding + scroll issues * fix scroll issues * improve scroll performance * fixes for safari * optimization and fixes * fixes to docs + details animation * padding fixes for code block * added tab animation * fixed incorrect link * added selection styling * fix lint errors * redesigned details component * added detailed feedback form * api reference fixes * fix tabs * upgrade + fixes * updated documentation links * optimizations to sidebar items * fix spacing in sidebar item * optimizations and fixes * fix endpoint path styling * remove margin * final fixes * change margin on small devices * generated OAS * fixes for mobile * added feedback modal * optimize dark mode button * fixed color mode useeffect * minimize dom size * use new style system * radius and spacing design system * design fixes * fix eslint errors * added meta files * change cron schedule * fix docusaurus configurations * added operating system to feedback data * change content directory name * fixes to contribution guidelines * revert renaming content * added api-reference to documentation workflow * fixes for search * added dark mode + fixes * oas fixes * handle bugs * added code examples for clients * changed tooltip text * change authentication to card * change page title based on selected section * redesigned mobile navbar * fix icon colors * fix key colors * fix medusa-js installation command * change external regex in algolia * change changeset * fix padding on mobile * fix hydration error * update depedencies
217 lines
6.9 KiB
Plaintext
217 lines
6.9 KiB
Plaintext
---
|
||
description: 'Learn how to add a middleware in Medusa. A middleware is a function that has access to the request and response objects and can be used to perform actions around an endpoint.'
|
||
addHowToData: true
|
||
---
|
||
|
||
import Troubleshooting from '@site/src/components/Troubleshooting'
|
||
import ServiceLifetimeSection from '../../troubleshooting/awilix-resolution-error/_service-lifetime.md'
|
||
import CustomRegistrationSection from '../../troubleshooting/awilix-resolution-error/_custom-registration.md'
|
||
|
||
# Middlewares
|
||
|
||
In this document, you’ll learn how to add a middleware to an existing or custom route in Medusa.
|
||
|
||
## Overview
|
||
|
||
As the Medusa backend is built on top of [Express](https://expressjs.com/), Express’s features can be utilized during your development with Medusa.
|
||
|
||
One feature in particular is adding a [middleware](http://expressjs.com/en/guide/using-middleware.html#using-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 backend, a route in a plugin, or your custom routes.
|
||
|
||
---
|
||
|
||
## How to Add a Middleware
|
||
|
||
### Step 1: Create the Middleware File
|
||
|
||
You can organize your middlewares as you see fit, but it's recommended to create Middlewares in the `src/api/middlewares` directory. It's recommended to create each middleware in a different file.
|
||
|
||
Each file should export a middleware function that accepts three parameters:
|
||
|
||
1. The first one is an Express request object. It can be used to get details related to the request or resolve resources from the dependency container.
|
||
2. The second one is an Express response object. It can be used to modify the response, or in some cases return a response without executing the associated endpoint.
|
||
3. The third one is a next middleware function that ensures that other middlewares and the associated endpoint are executed.
|
||
|
||
:::info
|
||
|
||
You can learn more about Middlewares and their capabilities in [Express’s documentation](http://expressjs.com/en/guide/using-middleware.html#using-middleware).
|
||
|
||
:::
|
||
|
||
Here's an example of a middleware:
|
||
|
||
```ts title=src/api/middlewares/custom-middleware.ts
|
||
export function customMiddleware(req, res, next) {
|
||
// TODO perform an action
|
||
|
||
next()
|
||
}
|
||
```
|
||
|
||
### Step 2: Apply Middleware on an Endpoint
|
||
|
||
To apply a middleware on any endpoint, you can use the same router defined in `src/api/index.ts` or any other router that is used or exported by `src/api/index.ts`. For example:
|
||
|
||
:::warning
|
||
|
||
The examples used here don't apply Cross-Origin Resource Origin (CORS) options for simplicity. Make sure to apply them, especially for core routes, as explained in the [Create Endpoint](./create.mdx#cors-configuration) documentation.
|
||
|
||
:::
|
||
|
||
```ts title=src/api/index.ts
|
||
import { Router } from "express"
|
||
import {
|
||
customMiddleware,
|
||
} from "./middlewares/custom-middleware"
|
||
|
||
export default (rootDirectory, pluginOptions) => {
|
||
const router = Router()
|
||
|
||
// custom route
|
||
router.get("/hello", (req, res) => {
|
||
res.json({
|
||
message: "Welcome to My Store!",
|
||
})
|
||
})
|
||
|
||
// middleware for the custom route
|
||
router.use("/hello", customMiddleware)
|
||
|
||
// middleware for core route
|
||
router.use("/store/products", customMiddleware)
|
||
|
||
return router
|
||
}
|
||
```
|
||
|
||
## Step 3: Building Files
|
||
|
||
Similar to custom endpoints, you must transpile the files under `src` into the `dist` directory for the backend to load them.
|
||
|
||
To do that, run the following command before running the Medusa backend:
|
||
|
||
```bash npm2yarn
|
||
npm run build
|
||
```
|
||
|
||
You can then test that the middleware is working by running the backend.
|
||
|
||
---
|
||
|
||
## Registering New Resources in Dependency Container
|
||
|
||
In some cases, you may need to register a resource to use within your commerce application. For example, you may want to register the logged-in user to access it in other services. You can do that in your middleware.
|
||
|
||
:::tip
|
||
|
||
If you want to register a logged-in user and access it in your resources, you can check out [this example guide](./example-logged-in-user.mdx).
|
||
|
||
:::
|
||
|
||
To register a new resource in the dependency container, use the `req.scope.register` method:
|
||
|
||
```ts title=src/api/middlewares/custom-middleware.ts
|
||
export function customMiddleware(req, res, next) {
|
||
// TODO perform an action
|
||
|
||
req.scope.register({
|
||
customResource: {
|
||
resolve: () => "my custom resource",
|
||
},
|
||
})
|
||
|
||
next()
|
||
}
|
||
```
|
||
|
||
You can then load this new resource within other resources. For example, to load it in a service:
|
||
|
||
<!-- eslint-disable prefer-rest-params -->
|
||
|
||
```ts title=src/services/custom-service.ts
|
||
import { TransactionBaseService } from "@medusajs/medusa"
|
||
|
||
class CustomService extends TransactionBaseService {
|
||
|
||
constructor(container, options) {
|
||
super(...arguments)
|
||
|
||
// use the registered resource.
|
||
try {
|
||
container.customResource
|
||
} catch (e) {
|
||
// avoid errors when the backend first loads
|
||
}
|
||
}
|
||
}
|
||
|
||
export default CustomService
|
||
```
|
||
|
||
Notice that you have to wrap your usage of the new resource in a try-catch block when you use it in a constructor. This is to avoid errors that can arise when the backend first loads, as the resource is not registered yet.
|
||
|
||
### Note About Services Lifetime
|
||
|
||
If you want to access new registrations in the dependency container within a service, you must set the lifetime of the service either to `Lifetime.SCOPED` or `Lifetime.TRANSIENT`. Services that have a `Lifetime.SINGLETON` lifetime can't access new registrations since they're resolved and cached in the root dependency container beforehand. You can learn more in the [Create Services documentation](../services/create-service.mdx#service-life-time).
|
||
|
||
For custom services, no additional action is required as the default lifetime is `Lifetime.SCOPED`. However, if you extend a core service, you must change the lifetime since the default lifetime for core services is `Lifetime.SINGLETON`.
|
||
|
||
For example:
|
||
|
||
<!-- eslint-disable prefer-rest-params -->
|
||
|
||
```ts
|
||
import { Lifetime } from "awilix"
|
||
import {
|
||
ProductService as MedusaProductService,
|
||
} from "@medusajs/medusa"
|
||
|
||
// extending ProductService from the core
|
||
class ProductService extends MedusaProductService {
|
||
// The default life time for a core service is SINGLETON
|
||
static LIFE_TIME = Lifetime.SCOPED
|
||
|
||
constructor(container, options) {
|
||
super(...arguments)
|
||
|
||
// use the registered resource.
|
||
try {
|
||
container.customResource
|
||
} catch (e) {
|
||
// avoid errors when the backend first loads
|
||
}
|
||
}
|
||
|
||
// ...
|
||
}
|
||
|
||
export default ProductService
|
||
```
|
||
|
||
---
|
||
|
||
## Troubleshooting
|
||
|
||
<Troubleshooting
|
||
sections={[
|
||
{
|
||
title: 'AwilixResolutionError: Could Not Resolve X',
|
||
content: <ServiceLifetimeSection />
|
||
},
|
||
{
|
||
title: 'AwilixResolutionError: Could Not Resolve X (Custom Registration)',
|
||
content: <CustomRegistrationSection />
|
||
}
|
||
]}
|
||
/>
|
||
|
||
---
|
||
|
||
## See Also
|
||
|
||
- [Store API reference](https://docs.medusajs.com/api/store)
|
||
- [Admin API reference](https://docs.medusajs.com/api/admin)
|