Best way to run some code only once on server start in Nuxt.js (and not during build)

Viewed 1575

While I wrote this answer for StackOverflow I came across the problem that I wanted to execute some code exactly once in Nuxt.js when the server is started (or while the server is starting).

I thought about writing a module or a plugin, but I did not succeed, since both were executed every time I contacted the server, i.e., every time I made a call to localhost:3000/myPage. Probably I am missing the right module hook or some plugin setting?

Since I could not find any information on this problem in the official documentation, I now came up with a quite ugly solution: I wrote a serverMiddleware that executes some code (the code that should be run only once) and then returns an empty handler - which now adds (little) unnecessary overhead to every request.

My question: What would have been the best way to execute some code exactly once on a Nuxt.js server during/after startup, but not during building?


Minimal ugly working example:

nuxt.config.js:

export default {
  ...
  serverMiddleware: [ "~/serverMiddleware/run-once.js" ]
  ...
}

~/serverMiddleware/run-once.js:

console.log("Yay, I only run once when the server is started!")
// Since we are a serverMiddleware, we have to return a handler, even if this it does nothing
// I think this is really ugly...
export default function (req, res, next) {
  next()
}

PS: I saw questions such as Is it possible for Nuxt JS plugins to only run once? but it seems to not answer my question since the vue-renderer:ssr:prepareContext nuxt hook also executes every time I send a request to the server.

Also, a module such as the following does not work since it is also executed during nuxt build and not only on nuxt dev or nuxt start:

export default function MyModuleThatShouldOnlyRunOnce (_moduleOptions) {
  console.log("I run on 'nuxt dev' and 'nuxt start', but sadly also on 'nuxt build' :(");
}
0 Answers
Related