title: How to authenticate in websockets, using node and express-ws
body: <p>I am using node 10.16.0, express 4.0.0 and <a href="https://www.npmjs.com/package/express-ws" rel="nofollow noreferrer">express-ws</a> module . In my normal routes that I use REST,  I am using a middleware to check if there is a header with a token and validate that token. </p>
  
  <p>How do I do the same thing for websockets? </p>
  
  <p>I cannot just add a header to ws and pass it to the node route, even though express-ws allows to easily create express-style routes. </p>
  
  <p>Currently, I am using an http server to create a ws server and then seperating different express routes</p>
  
  <pre><code>//app.js
  const app = express();
  
  const wsHttpServer = http.createServer();
  wsHttpServer.listen(5001);
  const expressWs = require('express-ws')(app , wsHttpServer);
  
  app.use(cors());
  
  app.use(express.static(path.join(__dirname,'public'))); 
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({extended:false}));
  app.use(express.json());
  app.use(express.urlencoded({extended:false})); 
  
  app.use('/ws', require('./routes/wsroute')); 
  app.use('/login', require('./routes/login'));
  
  
  const port = process.env.PORT || 4000;
  app.listen(port, ()=&gt;{
      console.log('server runs on port ', port);
  });
  
  exports.expressWs = expressWs;
  </code></pre>
  
  <p>and then for the ws routes, according to the express-ws examples </p>
  
  <pre><code>//wsroute.js
  router.ws('/users/:name/:date/:time', /*token.validate(),*/  (ws, req) =&gt; { 
      const name = req.params.name;  
      const date = req.params.date;
      const time = req.params.time;  
      console.log('ws route');
      console.log('ws route',name, date, time);    
  });
  </code></pre>
  
  <p>If I un-comment the <code>token.validate()</code> part, this will never control log because there is no header with a token.</p>
  
  <p>How can I add a header to ws, like I do in REST, so it can be checked automatically? I guess that if the ws server is initialized using an http server and the ws route also includes a <code>req</code>, I can somehow do it?</p>
  
  <p>Or is there another method? </p>
  
  <p>Thanks</p>