So I'm not 100% versed in the Nuxt lifecycle (v2.x), but afaik you CANNOT access the Nuxt app context during the serverMiddleware lifecycle phase. serverMiddleware
is really connect
-based (used internally by Express, btw) for processing req
, res
and next
parameters, which represent the request, the response, and next
which is connect
s flow management parameter.
The basic conceptual reason is that the Nuxt app context supports both the server and client-side, and the default 'universal' mode is a core objective of Nuxt. connect
is really a server-side only library designed to handle the request and response nature of an application server.
Since you need config.$db
, provided the configuration values you need are static, there may be an alternative way to use the nuxt.config env
and the general environment variables in serverMiddleware
. $config
is a newer Nuxt construct intended to allow more flexible runtime environment variables (as well as normal env vars).
Here is the current 2.x link to the middleware
vs serverMiddleware
explanation provided by Nuxt. I've also cut/paste the text info in case the link on Nuxt decays.
serverMiddleware vs middleware!
Don't confuse it with routes middleware
which are called before each route by Vue in Client Side or SSR. Middleware listed in the serverMiddleware
property runs server-side before vue-server-renderer and can be used for server specific tasks like handling API requests or serving assets.
Do not add serverMiddleware
to the middleware/ directory.
Middleware, are bundled by webpack into your production bundle and run on beforeRouteEnter. If you add serverMiddleware
to the middleware/ directory it will be wrongly picked up by Nuxt as middleware
and will add wrong dependencies to your bundle or generate errors.
Btw, as always, if I'm incorrect on any of the above, I'm always appreciative of Stackflow users who point out what is wrong or can be explained better