How to properly handle Node express graceful shutdown

If you’re building something in backend using Node.js, There’s a good chance that you’re using express.js. Express.js is most popular http framework know for being fast, unopinionated, and feature complete library.

One thing developers need to handle properly when using express with process managers like pm2, forever etc, when these process managers send shutdown signal, we need to do graceful shutdown of out nodejs or express app to avoid side effects. like finishing active requests before closing server, clean up resources, db connections etc.

In this tutorial, we will learn how to properly handle Shutdown in node.js or expres.js based shutdown signals like SIGTERM.

Node.js or Express.js graceful shutdown

const express = require("express");

const expressServerApp = express();

const port = 3000;

expressServerApp.get("/", (req, res) => {
  res.send("Hello World!");
});

expressServerApp.listen(port, () => {
  console.log(`Awesome app listening at http://localhost:${port}`);
});

function handleShutdownGracefully() {
  console.info("closing server gracefully...");

  expressServerApp.close(() => {
    console.info("server closed.");
    // close db connections here or
    // any other clean if required
    process.exit(0); // if required
  });
}

process.on("SIGINT", handleShutdownGracefully);
process.on("SIGTERM", handleShutdownGracefully);
process.on("SIGHUP", handleShutdownGracefully);

// official link: https://expressjs.com/en/advanced/healthcheck-graceful-shutdown.html

So now we can gracefully shutdown express server, after cleaning up resources, closing all file locks and finishing all active requests, we can also use same for any Node.js app to gracefully shutdown.

See also  Nodejs Monitor File Changes or modifications Tutorial

Leave a Comment