Server middleware ordering with modules

I think this message by @BracketJohn was ignored by @pi0 and @danielroe and other Nuxt core team mebers a lot of times - https://discord.com/channels/473401852243869706/473406169306890240/1046427324691787877 There are plenty of cases where you're authoring a module and installing a server middleware that attaches a context so that userland can access it as well when they have their own custom middleware - but this isnt the case. The custom middlewares you put inside server/middlewares will run first before the middleware added by modules. Before anyone answers "just add a number to your custom middleware so it runs last", no it does not work. It only works on the middlewares you put inside server/middlewares but not middlewares installed by modules. Is this something that will be tackled in the future? If not, is there a way to make sure middlewares added by modules (addServerMiddleware) will run first? Thank you so much!
3 Replies
TheSadMidDeveloper
TheSadMidDeveloperOP2mo ago
If you want more context, here: Say you're authoring a module. This is your middleware:
// runtime/server/middleware.ts
export default eventHandler((event ) => {
event.context.hello = 'world'
})
// runtime/server/middleware.ts
export default eventHandler((event ) => {
event.context.hello = 'world'
})
and in your module
addServerHandler({
middleware: true,
handler: resolver.resolve('./runtime/server/middleware'),
})
addServerHandler({
middleware: true,
handler: resolver.resolve('./runtime/server/middleware'),
})
and in your app, you install it like so:
export default defineNuxtConfig({
modules: ['your-nuxt-module'],
})
export default defineNuxtConfig({
modules: ['your-nuxt-module'],
})
Hooray! The middleware from module is installed. Now, you want to access that in your own custom middleware...
// server/middlewares/100.global.ts - see, it doesnt work even when you prefix it with that haha
export default eventHandler((event ) => {
console.log(event.context.hello) // undefined undefined undefined
})
// server/middlewares/100.global.ts - see, it doesnt work even when you prefix it with that haha
export default eventHandler((event ) => {
console.log(event.context.hello) // undefined undefined undefined
})
Oh no, the hello context is undefined!
danielroe
danielroe2mo ago
I spotted this in a github issue just a few hours ago maybe that would be a better place to discuss here: https://github.com/nuxt/nuxt/issues/26012 (though I'm sure it was a different issue I was reading - maybe there are several) but please, never think that pooya or I are ignoring it - it's more likely that a discord message is less likely to be spotted amidst other messages
TheSadMidDeveloper
TheSadMidDeveloperOP2mo ago
Sorry daniel and thank you
Want results from more Discord servers?
Add your server