How To Gracefully Shut Down Express.js

What happens when you try to shut down an Express.js server while a user is connected to it?

This is a simple express server that waits ten seconds before sending a response to a user.

Let’s find out what happens when I connect to it and shut the server down before it responds to me.

That could have been a visitor trying to create an account or a user uploading a file, and you just rudely interrupted them. Very uncool.

Thankfully there’s a (currently undocumented) way to make Express stop receiving new connections and wait til existing connections are closed before shutting down.

Express.js listen method returns an instance of the native Node.js http module. The http module has a close method which stops it from receiving new connections but waits til existing connections are served before shutting down.

With a few more lines of code, you too can make your Express.js server shut down gracefully 🙂

Get New Posts via Email

I don't always post, but when I do, you can get it sent directly to your inbox.

Join 8 other subscribers

  • Slava Fomin II

    I’ve implemented a more robust solution to gracefully shutdown Express applications and Node HTTP servers overall. I hope it could help someone: https://github.com/moebius-mlm/http-graceful-shutdown

    • This is very useful stuff, @slavafominii:disqus 🙂

      Is it possible to build conditional logic into the connection manager?

      For example ..
      Lets say my application has different tiers of users .. can I write code that ungracefully shuts down a free user’s connection but waits for paid users to finish their upload?

      • Slava Fomin II

        Thanks! It’s not implemented in the module itself, but such scenario if of course possible. You can create an issue in the repository so we can discuss it in more detail if your are interested.