title: Intercept (and potentially deny) web socket upgrade request
body: <p>I have a Node.js server that I am sending a web socket upgrade request to. The Authorization header of this request contains login information, which I need to compare against a database entry. I'm unsure how I can stop the web socket connection from opening until after my database query callback is executed.</p>
  
  <p>The following is a simplification of what I am currently doing:</p>
  
  <pre><code>var Express = require('express')
  var app = Express() 
  server = app.listen(app.get("port"), function () {})
  server.on("upgrade", function (request, socket) {
  //Query database
  //On success set "authenticated" flag on request (later accessed through socket.upgradeReq)
  //On failure abort connection
  })
  </code></pre>
  
  <p>This works, but there is a brief period of time where the socket is open but I haven't verified the Authorization header, so it would be possible for a malicious user to send/receive data. I'm mitigating this risk in my implementation through the use of an "authenticated" flag, but it seems like there must be a better way.</p>
  
  <p>I tried the following things, but while they seemed to intercept all requests except the upgrade ones:</p>
  
  <pre><code>Attempt #1: 
  app.use(function (request, response, next) {
  //Query database, only call next if authenticated
  next()
  })
  
  Attempt #2:
  app.all("*", function (request, response, next) {
  //Query database, only call next if authenticated
      next()
  })
  </code></pre>
  
  <p>Possibly worth noting:
  I do have an HTTP server as well, it uses the same port and accepts POST requests for registration and login.</p>
  
  <p>Thank you for any assistance, please let me know if additional information is needed.</p>