Skip to content

Commit c29a709

Browse files
authored
docs: changes for next release (medusajs#11708)
* docs: changes for next release * small fixes * fix lint error * small fix
1 parent 9e410be commit c29a709

File tree

6 files changed

+13658
-13354
lines changed

6 files changed

+13658
-13354
lines changed

www/apps/book/app/learn/fundamentals/api-routes/middlewares/page.mdx

+185-40
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,20 @@ As Medusa's server is based on Express, you can use any [Express middleware](htt
1818

1919
</Note>
2020

21+
### Middleware Types
22+
23+
There are two types of middlewares:
24+
25+
1. Global Middleware: A middleware that applies to all routes matching a specified pattern.
26+
2. Route Middleware: A middleware that applies to routes matching a specified pattern and HTTP method(s).
27+
28+
These middlewares generally have the same definition and usage, but they differ in the routes they apply to. You'll learn how to create both types in the following sections.
29+
2130
---
2231

23-
## How to Create a Middleware?
32+
## How to Create a Global Middleware?
2433

25-
Middlewares are defined in the special file `src/api/middlewares.ts`. Use the `defineMiddlewares` function from the Medusa Framework to define the middlewares, and export its value.
34+
Middlewares of all types are defined in the special file `src/api/middlewares.ts`. Use the `defineMiddlewares` function from the Medusa Framework to define the middlewares, and export its value.
2635

2736
For example:
2837

@@ -57,13 +66,69 @@ export default defineMiddlewares({
5766
The `defineMiddlewares` function accepts a middleware configurations object that has the property `routes`. `routes`'s value is an array of middleware route objects, each having the following properties:
5867

5968
- `matcher`: a string or regular expression indicating the API route path to apply the middleware on. The regular expression must be compatible with [path-to-regexp](https://github.com/pillarjs/path-to-regexp).
60-
- `middlewares`: An array of middleware functions.
69+
- `middlewares`: An array of global and route middleware functions.
70+
71+
In the example above, you define a global middleware that logs the message `Received a request!` whenever a request is sent to an API route path starting with `/custom`.
72+
73+
### Test the Global Middleware
74+
75+
To test the middleware:
76+
77+
1. Start the application:
78+
79+
```bash npm2yarn
80+
npm run dev
81+
```
6182

62-
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 `/custom`.
83+
2. Send a request to any API route starting with `/custom`.
84+
3. See the following message in the terminal:
85+
86+
```bash
87+
Received a request!
88+
```
6389

6490
---
6591

66-
## Test the Middleware
92+
## How to Create a Route Middleware?
93+
94+
In the previous section, you learned how to create a global middleware. You define the route middleware in the same way in `src/api/middlewares.ts`, but you specify an additional property `method` in the middleware route object. Its value is one or more HTTP methods to apply the middleware to.
95+
96+
For example:
97+
98+
export const highlights = [["12", "method", "Apply the middleware only on `POST` requests"]]
99+
100+
```ts title="src/api/middlewares.ts" highlights={highlights} collapsibleLines="1-7" expandButtonLabel="Show Imports"
101+
import {
102+
MedusaNextFunction,
103+
MedusaRequest,
104+
MedusaResponse,
105+
defineMiddlewares,
106+
} from "@medusajs/framework/http"
107+
108+
export default defineMiddlewares({
109+
routes: [
110+
{
111+
matcher: "/custom*",
112+
method: ["POST", "PUT"],
113+
middlewares: [
114+
(
115+
req: MedusaRequest,
116+
res: MedusaResponse,
117+
next: MedusaNextFunction
118+
) => {
119+
console.log("Received a request!")
120+
121+
next()
122+
},
123+
],
124+
},
125+
],
126+
})
127+
```
128+
129+
This example applies the middleware only when a `POST` or `PUT` request is sent to an API route path starting with `/custom`, changing the middleware from a global middleware to a route middleware.
130+
131+
### Test the Route Middleware
67132

68133
To test the middleware:
69134

@@ -73,7 +138,7 @@ To test the middleware:
73138
npm run dev
74139
```
75140

76-
2. Send a request to any API route starting with `/custom`.
141+
2. Send a `POST` request to any API route starting with `/custom`.
77142
3. See the following message in the terminal:
78143

79144
```bash
@@ -141,15 +206,13 @@ This applies a middleware to the routes defined in the file `src/api/custom/[id]
141206

142207
---
143208

144-
## Restrict HTTP Methods
145-
146-
Restrict which HTTP methods the middleware is applied to using the `method` property of the middleware route object.
209+
## Request URLs with Trailing Backslashes
147210

148-
For example:
211+
A middleware whose `matcher` pattern doesn't end with a backslash won't be applied for requests to URLs with a trailing backslash.
149212

150-
export const highlights = [["12", "method", "Apply the middleware only on `POST` requests"]]
213+
For example, consider you have the following middleware:
151214

152-
```ts title="src/api/middlewares.ts" highlights={highlights} collapsibleLines="1-7" expandButtonLabel="Show Imports"
215+
```ts title="src/api/middlewares.ts" collapsibleLines="1-7" expandMoreLabel="Show Imports"
153216
import {
154217
MedusaNextFunction,
155218
MedusaRequest,
@@ -160,48 +223,126 @@ import {
160223
export default defineMiddlewares({
161224
routes: [
162225
{
163-
matcher: "/custom*",
164-
method: ["POST", "PUT"],
226+
matcher: "/custom",
165227
middlewares: [
166-
// ...
228+
(
229+
req: MedusaRequest,
230+
res: MedusaResponse,
231+
next: MedusaNextFunction
232+
) => {
233+
console.log("Received a request!")
234+
235+
next()
236+
},
167237
],
168238
},
169239
],
170240
})
171241
```
172242

173-
`method`'s value is one or more HTTP methods to apply the middleware to.
243+
If you send a request to `http://localhost:9000/custom`, the middleware will run.
244+
245+
However, if you send a request to `http://localhost:9000/custom/`, the middleware won't run.
174246

175-
This example applies the middleware only when a `POST` or `PUT` request is sent to an API route path starting with `/custom`.
247+
In general, avoid adding trailing backslashes when sending requests to API routes.
176248

177249
---
178250

179-
## Request URLs with Trailing Backslashes
251+
## Middlewares and Route Ordering
180252

181-
A middleware whose `matcher` pattern doesn't end with a backslash won't be applied for requests to URLs with a trailing backslash.
253+
<Note>
182254

183-
For example, consider you have the following middleware:
255+
The ordering explained in this section was added in [Medusa v2.6](https://github.com/medusajs/medusa/releases/tag/v2.6)
184256

185-
```ts collapsibleLines="1-7" expandMoreLabel="Show Imports"
186-
import {
187-
MedusaNextFunction,
188-
MedusaRequest,
189-
MedusaResponse,
190-
defineMiddlewares,
191-
} from "@medusajs/framework/http"
257+
</Note>
258+
259+
The Medusa application registers middlewares and API route handlers in the following order:
260+
261+
1. Global middlewares in the following order:
262+
1. Global middleware defined in the Medusa's core.
263+
2. Global middleware defined in the plugins (in the order the plugins are registered in).
264+
3. Global middleware you define in the application.
265+
2. Route middlewares in the following order:
266+
1. Route middleware defined in the Medusa's core.
267+
2. Route middleware defined in the plugins (in the order the plugins are registered in).
268+
3. Route middleware you define in the application.
269+
3. API routes in the following order:
270+
1. API routes defined in the Medusa's core.
271+
2. API routes defined in the plugins (in the order the plugins are registered in).
272+
3. API routes you define in the application.
273+
274+
### Middlewares Sorting
275+
276+
On top of the previous ordering, Medusa sorts global and route middlewares based on their matcher pattern in the following order:
192277

278+
1. Wildcard matchers. For example, `/custom*`.
279+
2. Regex matchers. For example, `/custom/(products|collections)`.
280+
3. Static matchers without parameters. For example, `/custom`.
281+
4. Static matchers with parameters. For example, `/custom/:id`.
282+
283+
For example, if you have the following middlewares:
284+
285+
```ts title="src/api/middlewares.ts"
193286
export default defineMiddlewares({
194287
routes: [
288+
{
289+
matcher: "/custom/:id",
290+
middlewares: [/* ... */],
291+
},
195292
{
196293
matcher: "/custom",
197-
middlewares: [
198-
(
199-
req: MedusaRequest,
200-
res: MedusaResponse,
201-
next: MedusaNextFunction
202-
) => {
203-
console.log("Received a request!")
294+
middlewares: [/* ... */],
295+
},
296+
{
297+
matcher: "/custom*",
298+
method: ["GET"],
299+
middlewares: [/* ... */],
300+
},
301+
{
302+
matcher: "/custom/:id",
303+
method: ["GET"],
304+
middlewares: [/* ... */],
305+
},
306+
],
307+
})
308+
```
309+
310+
The global middlewares are sorted into the following order before they're registered:
311+
312+
1. Global middleware `/custom`.
313+
2. Global middleware `/custom/:id`.
314+
315+
And the route middlewares are sorted into the following order before they're registered:
316+
317+
1. Route middleware `/custom*`.
318+
2. Route middleware `/custom/:id`.
319+
320+
Then, the middlwares are registered in the order mentioned earlier, with global middlewares first, then the route middlewares.
321+
322+
### Middlewares and Route Execution Order
323+
324+
When a request is sent to an API route, the global middlewares are executed first, then the route middlewares, and finally the route handler.
325+
326+
For example, consider you have the following middlewares:
204327

328+
```ts title="src/api/middlewares.ts"
329+
export default defineMiddlewares({
330+
routes: [
331+
{
332+
matcher: "/custom",
333+
middlewares: [
334+
(req, res, next) => {
335+
console.log("Global middleware")
336+
next()
337+
},
338+
],
339+
},
340+
{
341+
matcher: "/custom",
342+
method: ["GET"],
343+
middlewares: [
344+
(req, res, next) => {
345+
console.log("Route middleware")
205346
next()
206347
},
207348
],
@@ -210,16 +351,20 @@ export default defineMiddlewares({
210351
})
211352
```
212353

213-
If you send a request to `http://localhost:9000/custom`, the middleware will run.
354+
When you send a request to `/custom` route, the following messages are logged in the terminal:
214355

215-
However, if you send a request to `http://localhost:9000/custom/`, the middleware won't run.
356+
```bash
357+
Global middleware
358+
Route middleware
359+
Hello from custom! # message logged from API route handler
360+
```
216361

217-
In general, avoid adding trailing backslashes when sending requests to API routes.
362+
The global middleware runs first, then the route middleware, and finally the route handler, assuming that it logs the message `Hello from custom!`.
218363

219364
---
220365

221-
## Middlewares Precedence in Registration
366+
## Overriding Middlewares
222367

223-
The Medusa application registers your middlewares first, then registers middlewares defined in Medusa's core.
368+
A middleware can not override an existing middleware. Instead, middlewares are added to the end of the middleware stack.
224369

225-
So, if you add a middleware for a route defined in the core, it might get overridden by the core middleware. For example, if you add a middleware to change authentication of admin routes, the authentication middleware defined in the core will still run, leading to your middleware not being effective.
370+
For example, if you define a custom validation middleware, such as `validateAndTransformBody`, on an existing route, then both the original and the custom validation middleware will run.

www/apps/book/generated/edit-dates.mjs

+1-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ export const generatedEditDates = {
5353
"app/learn/fundamentals/admin/tips/page.mdx": "2025-02-24T09:52:06.901Z",
5454
"app/learn/fundamentals/api-routes/cors/page.mdx": "2024-12-09T13:04:04.357Z",
5555
"app/learn/fundamentals/admin/ui-routes/page.mdx": "2025-02-24T09:35:11.752Z",
56-
"app/learn/fundamentals/api-routes/middlewares/page.mdx": "2025-02-12T17:05:20.708Z",
56+
"app/learn/fundamentals/api-routes/middlewares/page.mdx": "2025-03-04T10:16:15.029Z",
5757
"app/learn/fundamentals/modules/isolation/page.mdx": "2024-12-09T11:02:38.087Z",
5858
"app/learn/fundamentals/data-models/configure-properties/page.mdx": "2024-10-21T13:30:21.368Z",
5959
"app/learn/fundamentals/data-models/index/page.mdx": "2024-10-21T13:30:21.368Z",

0 commit comments

Comments
 (0)