Skip to content

Commit 94b62c6

Browse files
authored
fix: initiate request container before other express middleware (medusajs#12761)
1 parent ffa611b commit 94b62c6

File tree

3 files changed

+23
-7
lines changed

3 files changed

+23
-7
lines changed

.changeset/tricky-plants-sell.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@medusajs/medusa": patch
3+
"@medusajs/framework": patch
4+
---
5+
6+
fix: fallback to console with req.scope is undefined

packages/core/framework/src/http/middlewares/error-handler.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,20 @@ export function errorHandler() {
2020
res: Response,
2121
_: NextFunction
2222
) {
23-
const logger = req.scope.resolve(ContainerRegistrationKeys.LOGGER)
23+
const logger = req.scope
24+
? req.scope.resolve(ContainerRegistrationKeys.LOGGER)
25+
: console
2426

25-
err = formatException(err)
27+
if (!req.scope) {
28+
logger.error(
29+
"req.scope is missing unexpectedly. It should be defined in all the cases"
30+
)
31+
}
2632

33+
err = formatException(err)
2734
logger.error(err)
2835

2936
const errorType = err.type || err.name
30-
3137
const errObj = {
3238
code: err.code,
3339
type: err.type,

packages/medusa/src/loaders/index.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -89,10 +89,10 @@ async function loadEntrypoints(
8989
return async () => {}
9090
}
9191

92-
const { shutdown } = await expressLoader({
93-
app: expressApp,
94-
})
95-
92+
/**
93+
* The scope and the ip address must be fetched before we execute any other
94+
* middleware
95+
*/
9696
expressApp.use((req: Request, res: Response, next: NextFunction) => {
9797
req.scope = container.createScope() as MedusaContainer
9898
req.requestId = (req.headers["x-request-id"] as string) ?? v4()
@@ -108,6 +108,10 @@ async function loadEntrypoints(
108108
next()
109109
})
110110

111+
const { shutdown } = await expressLoader({
112+
app: expressApp,
113+
})
114+
111115
await adminLoader({ app: expressApp, configModule, rootDirectory, plugins })
112116
await apiLoader({
113117
container,

0 commit comments

Comments
 (0)