|
1
|
import { Table, CodeTabs, CodeTab } from "docs-ui" |
|
2
|
|
|
3
|
export const metadata = { |
|
4
|
title: `${pageNumber} Middlewares`, |
|
5
|
} |
|
6
|
|
|
7
|
# {metadata.title} |
|
8
|
|
|
9
|
In this chapter, you’ll learn about middlewares and how to create them. |
|
10
|
|
|
11
|
## What is a Middleware? |
|
12
|
|
|
13
|
A middleware is a function executed when a request is sent to an API Route. It's executed before the route handler function. |
|
14
|
|
|
15
|
Middlewares are used to guard API routes, parse request content types other than `application/json`, manipulate request data, and more. |
|
16
|
|
|
17
|
 |
|
18
|
|
|
19
|
<Note title="Tip"> |
|
20
|
|
|
21
|
As Medusa's server is based on Express, you can use any [Express middleware](https://expressjs.com/en/resources/middleware.html). |
|
22
|
|
|
23
|
</Note> |
|
24
|
|
|
25
|
### Middleware Types |
|
26
|
|
|
27
|
There are two types of middlewares: |
|
28
|
|
|
29
|
<Table> |
|
30
|
<Table.Header> |
|
31
|
<Table.Row> |
|
32
|
<Table.HeaderCell> |
|
33
|
Type |
|
34
|
</Table.HeaderCell> |
|
35
|
<Table.HeaderCell> |
|
36
|
Description |
|
37
|
</Table.HeaderCell> |
|
38
|
<Table.HeaderCell> |
|
39
|
Example |
|
40
|
</Table.HeaderCell> |
|
41
|
</Table.Row> |
|
42
|
</Table.Header> |
|
43
|
<Table.Body> |
|
44
|
<Table.Row> |
|
45
|
<Table.Cell> |
|
46
|
Global Middleware |
|
47
|
</Table.Cell> |
|
48
|
<Table.Cell> |
|
49
|
A middleware that applies to all routes matching a specified pattern. |
|
50
|
</Table.Cell> |
|
51
|
<Table.Cell> |
|
52
|
`/custom*` applies to all routes starting with `/custom` |
|
53
|
</Table.Cell> |
|
54
|
</Table.Row> |
|
55
|
<Table.Row> |
|
56
|
<Table.Cell> |
|
57
|
Route Middleware |
|
58
|
</Table.Cell> |
|
59
|
<Table.Cell> |
|
60
|
A middleware that applies to routes matching a specified pattern and HTTP method(s). |
|
61
|
</Table.Cell> |
|
62
|
<Table.Cell> |
|
63
|
A middleware that applies to all `POST` requests to routes starting with `/custom`. |
|
64
|
</Table.Cell> |
|
65
|
</Table.Row> |
|
66
|
</Table.Body> |
|
67
|
</Table> |
|
68
|
|
|
69
|
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. |
|
70
|
|
|
71
|
--- |
|
72
|
|
|
73
|
## How to Create a Middleware? |
|
74
|
|
|
75
|
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. |
|
76
|
|
|
77
|
For example: |
|
78
|
|
|
79
|
<CodeTabs group="middleware-type"> |
|
80
|
<CodeTab label="Global Middleware" value="global-middleware"> |
|
81
|
|
|
82
|
```ts title="src/api/middlewares.ts" |
|
83
|
import { |
|
84
|
defineMiddlewares, |
|
85
|
MedusaNextFunction, |
|
86
|
MedusaRequest, |
|
87
|
MedusaResponse, |
|
88
|
} from "@medusajs/framework/http" |
|
89
|
|
|
90
|
export default defineMiddlewares({ |
|
91
|
routes: [ |
|
92
|
{ |
|
93
|
matcher: "/custom*", |
|
94
|
middlewares: [ |
|
95
|
( |
|
96
|
req: MedusaRequest, |
|
97
|
res: MedusaResponse, |
|
98
|
next: MedusaNextFunction |
|
99
|
) => { |
|
100
|
console.log("Received a request!") |
|
101
|
|
|
102
|
next() |
|
103
|
}, |
|
104
|
], |
|
105
|
}, |
|
106
|
], |
|
107
|
}) |
|
108
|
``` |
|
109
|
|
|
110
|
</CodeTab> |
|
111
|
<CodeTab label="Route Middleware" value="route-middleware"> |
|
112
|
|
|
113
|
export const highlights = [["12", "method", "Apply the middleware only on `POST` requests"]] |
|
114
|
|
|
115
|
```ts title="src/api/middlewares.ts" highlights={highlights} |
|
116
|
import { |
|
117
|
defineMiddlewares, |
|
118
|
MedusaNextFunction, |
|
119
|
MedusaRequest, |
|
120
|
MedusaResponse, |
|
121
|
} from "@medusajs/framework/http" |
|
122
|
|
|
123
|
export default defineMiddlewares({ |
|
124
|
routes: [ |
|
125
|
{ |
|
126
|
matcher: "/custom*", |
|
127
|
method: ["POST", "PUT"], |
|
128
|
middlewares: [ |
|
129
|
( |
|
130
|
req: MedusaRequest, |
|
131
|
res: MedusaResponse, |
|
132
|
next: MedusaNextFunction |
|
133
|
) => { |
|
134
|
console.log("Received a request!") |
|
135
|
|
|
136
|
next() |
|
137
|
}, |
|
138
|
], |
|
139
|
}, |
|
140
|
], |
|
141
|
}) |
|
142
|
``` |
|
143
|
|
|
144
|
</CodeTab> |
|
145
|
</CodeTabs> |
|
146
|
|
|
147
|
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: |
|
148
|
|
|
149
|
- `matcher`: the API route path to apply the middleware on. Its value can be one of the following: |
|
150
|
- A string, which Medusa compiles using [path-to-regexp](https://github.com/pillarjs/path-to-regexp). So, the string can include patterns like `/custom*`. |
|
151
|
- A regular expression (`RegExp`), which Medusa matches against the request path directly. For example, `/^\/custom(\/.*)?$/`. |
|
152
|
|
|
153
|
- `middlewares`: An array of global and route middleware functions. |
|
154
|
- `method`: (optional) By default, a middleware is applied on all HTTP methods for a route. You can specify one or more HTTP methods to apply the middleware to in this option, making it a route middleware. |
|
155
|
|
|
156
|
### Test the Middleware |
|
157
|
|
|
158
|
To test the middleware: |
|
159
|
|
|
160
|
1. Start the application: |
|
161
|
|
|
162
|
```bash npm2yarn |
|
163
|
npm run dev |
|
164
|
``` |
|
165
|
|
|
166
|
2. Send a request to any API route starting with `/custom`. If you specified an HTTP method in the `method` property, make sure to use that method. |
|
167
|
3. See the following message in the terminal: |
|
168
|
|
|
169
|
```bash |
|
170
|
Received a request! |
|
171
|
``` |
|
172
|
|
|
173
|
### Troubleshooting |
|
174
|
|
|
175
|
If the middleware didn't run, make sure you've correctly created the middleware at `src/api/middlewares.ts` (with correct spelling). This is a common mistake that can lead to the middleware not being applied, resulting in unexpected behavior. |
|
176
|
|
|
177
|
--- |
|
178
|
|
|
179
|
## Apply a Middleware Using a Regular Expression |
|
180
|
|
|
181
|
You can set the `matcher` property to a regular expression (`RegExp`) to apply a middleware to routes matching a pattern. |
|
182
|
|
|
183
|
A `RegExp` matcher must account for the full request path, including the leading slash. How Medusa matches the pattern depends on whether the middleware is a global or route middleware. |
|
184
|
|
|
185
|
### Global Middleware |
|
186
|
|
|
187
|
For a global middleware (a middleware without a `method`), Medusa registers the `RegExp` using Express's [app.use](https://expressjs.com/en/4x/api.html#app.use) method. Express matches a `RegExp` in `app.use` only if the pattern matches from the start of the request path. |
|
188
|
|
|
189
|
So, you must anchor the pattern with `^` and include the leading slash: |
|
190
|
|
|
191
|
```ts title="src/api/middlewares.ts" |
|
192
|
import { defineMiddlewares } from "@medusajs/framework/http" |
|
193
|
|
|
194
|
export default defineMiddlewares({ |
|
195
|
routes: [ |
|
196
|
{ |
|
197
|
matcher: /^\/custom(\/.*)?$/, |
|
198
|
middlewares: [ |
|
199
|
// ... |
|
200
|
], |
|
201
|
}, |
|
202
|
], |
|
203
|
}) |
|
204
|
``` |
|
205
|
|
|
206
|
This middleware applies to `/custom` and any route starting with `/custom/`. |
|
207
|
|
|
208
|
<Note title="Warning" type="warning"> |
|
209
|
|
|
210
|
An unanchored pattern like `/custom/` doesn't match any route for a global middleware, since its match doesn't start at the beginning of the path. Always anchor a global middleware's pattern with `^\/`. |
|
211
|
|
|
212
|
</Note> |
|
213
|
|
|
214
|
### Route Middleware |
|
215
|
|
|
216
|
For a route middleware (a middleware with a `method`), Medusa matches the `RegExp` against the full request path. So, an unanchored pattern like `/custom/` matches routes containing `custom`. |
|
217
|
|
|
218
|
To keep the same behavior across both middleware types, always anchor a `RegExp` matcher with `^\/`. |
|
219
|
|
|
220
|
--- |
|
221
|
|
|
222
|
## When to Use Middlewares |
|
223
|
|
|
224
|
Middlewares are useful for: |
|
225
|
|
|
226
|
- [Protecting API routes](../protected-routes/page.mdx) to ensure that only authenticated users can access them. |
|
227
|
- [Validating](../validation/page.mdx) request query and body parameters. |
|
228
|
- [Parsing](../parse-body/page.mdx) request content types other than `application/json`. |
|
229
|
- [Applying CORS](../cors/page.mdx) configurations to custom API routes. |
|
230
|
|
|
231
|
--- |
|
232
|
|
|
233
|
## Middleware Function Parameters |
|
234
|
|
|
235
|
The middleware function accepts three parameters: |
|
236
|
|
|
237
|
1. A request object of type `MedusaRequest`. |
|
238
|
2. A response object of type `MedusaResponse`. |
|
239
|
3. A function of type `MedusaNextFunction` that executes the next middleware in the stack. |
|
240
|
|
|
241
|
<Note title="Important"> |
|
242
|
|
|
243
|
You must call the `next` function in the middleware. Otherwise, other middlewares and the API route handler won’t execute. |
|
244
|
|
|
245
|
</Note> |
|
246
|
|
|
247
|
For example: |
|
248
|
|
|
249
|
```ts title="src/api/middlewares.ts" |
|
250
|
import { |
|
251
|
MedusaNextFunction, |
|
252
|
MedusaRequest, |
|
253
|
MedusaResponse, |
|
254
|
defineMiddlewares, |
|
255
|
} from "@medusajs/framework/http" |
|
256
|
|
|
257
|
export default defineMiddlewares({ |
|
258
|
routes: [ |
|
259
|
{ |
|
260
|
matcher: "/custom*", |
|
261
|
middlewares: [ |
|
262
|
( |
|
263
|
req: MedusaRequest, |
|
264
|
res: MedusaResponse, |
|
265
|
next: MedusaNextFunction |
|
266
|
) => { |
|
267
|
console.log("Received a request!", req.body) |
|
268
|
|
|
269
|
next() |
|
270
|
}, |
|
271
|
], |
|
272
|
}, |
|
273
|
], |
|
274
|
}) |
|
275
|
``` |
|
276
|
|
|
277
|
This middleware logs the request body to the terminal, then calls the `next` function to execute the next middleware in the stack. |
|
278
|
|
|
279
|
--- |
|
280
|
|
|
281
|
## Middleware for Routes with Path Parameters |
|
282
|
|
|
283
|
To indicate a path parameter in a middleware's `matcher` pattern, use the format `:{param-name}`. |
|
284
|
|
|
285
|
<Note title="Tip"> |
|
286
|
|
|
287
|
A middleware applied on a route with path parameters is a route middleware. |
|
288
|
|
|
289
|
</Note> |
|
290
|
|
|
291
|
For example: |
|
292
|
|
|
293
|
export const pathParamHighlights = [["11", ":id", "Indicates that the API route accepts an `id` path parameter."]] |
|
294
|
|
|
295
|
```ts title="src/api/middlewares.ts" collapsibleLines="1-7" expandMoreLabel="Show Imports" highlights={pathParamHighlights} |
|
296
|
import { |
|
297
|
MedusaNextFunction, |
|
298
|
MedusaRequest, |
|
299
|
MedusaResponse, |
|
300
|
defineMiddlewares, |
|
301
|
} from "@medusajs/framework/http" |
|
302
|
|
|
303
|
export default defineMiddlewares({ |
|
304
|
routes: [ |
|
305
|
{ |
|
306
|
matcher: "/custom/:id", |
|
307
|
middlewares: [ |
|
308
|
// ... |
|
309
|
], |
|
310
|
}, |
|
311
|
], |
|
312
|
}) |
|
313
|
``` |
|
314
|
|
|
315
|
This applies a middleware to the routes defined in the file `src/api/custom/[id]/route.ts`. |
|
316
|
|
|
317
|
--- |
|
318
|
|
|
319
|
## Request URLs with Trailing Backslashes |
|
320
|
|
|
321
|
A middleware whose `matcher` pattern doesn't end with a backslash won't be applied for requests to URLs with a trailing backslash. |
|
322
|
|
|
323
|
For example, consider you have the following middleware: |
|
324
|
|
|
325
|
```ts title="src/api/middlewares.ts" collapsibleLines="1-7" expandMoreLabel="Show Imports" |
|
326
|
import { |
|
327
|
MedusaNextFunction, |
|
328
|
MedusaRequest, |
|
329
|
MedusaResponse, |
|
330
|
defineMiddlewares, |
|
331
|
} from "@medusajs/framework/http" |
|
332
|
|
|
333
|
export default defineMiddlewares({ |
|
334
|
routes: [ |
|
335
|
{ |
|
336
|
matcher: "/custom", |
|
337
|
middlewares: [ |
|
338
|
( |
|
339
|
req: MedusaRequest, |
|
340
|
res: MedusaResponse, |
|
341
|
next: MedusaNextFunction |
|
342
|
) => { |
|
343
|
console.log("Received a request!") |
|
344
|
|
|
345
|
next() |
|
346
|
}, |
|
347
|
], |
|
348
|
}, |
|
349
|
], |
|
350
|
}) |
|
351
|
``` |
|
352
|
|
|
353
|
If you send a request to `http://localhost:9000/custom`, the middleware will run. |
|
354
|
|
|
355
|
However, if you send a request to `http://localhost:9000/custom/`, the middleware won't run. |
|
356
|
|
|
357
|
In general, avoid adding trailing backslashes when sending requests to API routes. |
|
358
|
|
|
359
|
--- |
|
360
|
|
|
361
|
## How Are Middlewares Ordered and Applied? |
|
362
|
|
|
363
|
<Note> |
|
364
|
|
|
365
|
The information explained in this section is applicable starting from [Medusa v2.6](https://github.com/medusajs/medusa/releases/tag/v2.6). |
|
366
|
|
|
367
|
</Note> |
|
368
|
|
|
369
|
### Middleware and Routes Execution Order |
|
370
|
|
|
371
|
The Medusa application registers middlewares and API route handlers in the following order, stacking them on top of each other: |
|
372
|
|
|
373
|
 |
|
374
|
|
|
375
|
1. Global middlewares in the following order: |
|
376
|
1. Global middleware defined in the Medusa's core. |
|
377
|
2. Global middleware defined in the plugins (in the order the plugins are registered in). |
|
378
|
3. Global middleware you define in the application. |
|
379
|
2. Route middlewares in the following order: |
|
380
|
1. Route middleware defined in the Medusa's core. |
|
381
|
2. Route middleware defined in the plugins (in the order the plugins are registered in). |
|
382
|
3. Route middleware you define in the application. |
|
383
|
3. API routes in the following order: |
|
384
|
1. API routes defined in the Medusa's core. |
|
385
|
2. API routes defined in the plugins (in the order the plugins are registered in). |
|
386
|
3. API routes you define in the application. |
|
387
|
|
|
388
|
Then, when a request is sent to an API route, the stack is executed in order: global middlewares are executed first, then the route middlewares, and finally the route handlers. |
|
389
|
|
|
390
|
 |
|
391
|
|
|
392
|
For example, consider you have the following middlewares: |
|
393
|
|
|
394
|
```ts title="src/api/middlewares.ts" |
|
395
|
export default defineMiddlewares({ |
|
396
|
routes: [ |
|
397
|
{ |
|
398
|
matcher: "/custom", |
|
399
|
middlewares: [ |
|
400
|
(req, res, next) => { |
|
401
|
console.log("Global middleware") |
|
402
|
next() |
|
403
|
}, |
|
404
|
], |
|
405
|
}, |
|
406
|
{ |
|
407
|
matcher: "/custom", |
|
408
|
method: ["GET"], |
|
409
|
middlewares: [ |
|
410
|
(req, res, next) => { |
|
411
|
console.log("Route middleware") |
|
412
|
next() |
|
413
|
}, |
|
414
|
], |
|
415
|
}, |
|
416
|
], |
|
417
|
}) |
|
418
|
``` |
|
419
|
|
|
420
|
When you send a request to `/custom` route, the following messages are logged in the terminal: |
|
421
|
|
|
422
|
```bash |
|
423
|
Global middleware |
|
424
|
Route middleware |
|
425
|
Hello from custom! # message logged from API route handler |
|
426
|
``` |
|
427
|
|
|
428
|
The global middleware runs first, then the route middleware, and finally the route handler, assuming that it logs the message `Hello from custom!`. |
|
429
|
|
|
430
|
### Middlewares Sorting |
|
431
|
|
|
432
|
On top of the previous ordering, Medusa sorts global and route middlewares based on their matcher pattern in the following order: |
|
433
|
|
|
434
|
1. Wildcard matchers. For example, `/custom*`. |
|
435
|
2. Regex matchers. For example, `/custom/(products|collections)`. |
|
436
|
3. Static matchers without parameters. For example, `/custom`. |
|
437
|
4. Static matchers with parameters. For example, `/custom/:id`. |
|
438
|
|
|
439
|
For example, if you have the following middlewares: |
|
440
|
|
|
441
|
```ts title="src/api/middlewares.ts" |
|
442
|
export default defineMiddlewares({ |
|
443
|
routes: [ |
|
444
|
{ |
|
445
|
matcher: "/custom/:id", |
|
446
|
middlewares: [/* ... */], |
|
447
|
}, |
|
448
|
{ |
|
449
|
matcher: "/custom", |
|
450
|
middlewares: [/* ... */], |
|
451
|
}, |
|
452
|
{ |
|
453
|
matcher: "/custom*", |
|
454
|
method: ["GET"], |
|
455
|
middlewares: [/* ... */], |
|
456
|
}, |
|
457
|
{ |
|
458
|
matcher: "/custom/:id", |
|
459
|
method: ["GET"], |
|
460
|
middlewares: [/* ... */], |
|
461
|
}, |
|
462
|
], |
|
463
|
}) |
|
464
|
``` |
|
465
|
|
|
466
|
The global middlewares are sorted into the following order before they're registered: |
|
467
|
|
|
468
|
1. Global middleware `/custom`. |
|
469
|
2. Global middleware `/custom/:id`. |
|
470
|
|
|
471
|
And the route middlewares are sorted into the following order before they're registered: |
|
472
|
|
|
473
|
1. Route middleware `/custom*`. |
|
474
|
2. Route middleware `/custom/:id`. |
|
475
|
|
|
476
|
 |
|
477
|
|
|
478
|
Then, the middlwares are registered in the order mentioned earlier, with global middlewares first, then the route middlewares. |
|
479
|
|
|
480
|
--- |
|
481
|
|
|
482
|
## Overriding Middlewares |
|
483
|
|
|
484
|
A middleware can not override an existing middleware. Instead, middlewares are added to the end of the middleware stack. |
|
485
|
|
|
486
|
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. |
|
487
|
|
|
488
|
Similarly, if you add an [authenticate](../protected-routes/page.mdx#protect-custom-api-routes) middleware to an existing route, both the original and the custom authentication middleware will run. So, you can't override the original authentication middleware. |
|
489
|
|
|
490
|
### Alternative Solution to Overriding Middlewares |
|
491
|
|
|
492
|
If you need to change the middlewares applied to a route, you can create a custom [API route](../page.mdx) that executes the same functionality as the original route, but with the middlewares you want. |
|
493
|
|
|
494
|
Learn more in the [Override API Routes](../override/page.mdx) chapter. |