How to implement startup sanity checks in Nuxt3 server (nitro)?

30 views Asked by At

I have a simple webapp written in Nuxt3 which reads some environment variables as configs to run. For example, it reads DATA_DIR to know where it should read/write data to, and this config is critical, meaning - the webapp can't function without a valid DATA_DIR value.

I would like to run some code at server startup to perform some sanity checks as the server comes up, and fail the server (stop it before it starts listening on a port) with a helpful error message(s).

This comes up to 2 questions:

  1. How to run code in the server before it starts listening but after it read the configs?
  2. How to tell the server to shutdown at this point?

Ideally, I'm looking for something like this:

//this is made up - but ideally something similar exists and runs before the server start listening
defineNitroStartup((nitroApp) => {
  const dataDir = nitroApp.getConfig("dataDir")
  if (typeof dataDir !== 'string') {
    console.error("FATAL: dataDir must be defined")
    nitroApp.exit(1) //also made up, but I hope something similar exists
  }
}

Of course, if there's a different way to define config validation, in such a way that the server won't start listening if it fails, that would be even better, but I didn't find any in the docs...

0

There are 0 answers