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?

var app = require('express')();

app.get('/', function( req, res ){
  
  // respond after 10s
  
  setTimeout( function(){ 
    res.send( 'all done!' ); 
  }, 10000 );
});

app.listen( 5000 );

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.

var app = require('express')(),
    http_instance;

app.get('/', function( req, res ){
  
  setTimeout( function(){ 
    res.send( 'all done!' ); 
  }, 10000 );
});

// when shutdown signal is received, do graceful shutdown
process.on( 'SIGINT', function(){
  http_instance.close( function(){
    console.log( 'gracefully shutting down :)' );
    process.exit();
  });
});

http_instance = app.listen( 5000 );

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 🙂