'How to gracefully shut down nuxt.js + serverMiddleware + express after an unhandled rejection

TLDR: Is there a way to programmatically and properly shut down the Nuxt server while in the serverMiddleware?


I recently learned how create my own API inside Nuxt 2 through serverMiddleware. Before knowing serverMiddleware, I had to run my API in a separate backend. So I think I'm familiar with handling unhandled rejections.

Here's an example of my express backend code:

const express = require('express')
const app = express()

const port = process.env.PORT

const server = app.listen(port, () => {
    console.log(`App is running on port ${port}`)
}) 

process.on("unhandledRejection", (err) => {
    console.log(err.name, err.message);
    console.log("Unhandled Rejection. Shutting Down.");
    server.close(() => {
      process.exit(1);  
    });
});

Now when using Nuxt, app.listen() and server.close() doesn't work because Nuxt is running its own server. While process.exit(1) does the job, from what I understand, that by itself isn't ideal.

Is there a way to programmatically and properly shut down the Nuxt server while in the serverMiddleware?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source