Files
Damien Arrachequesne 0bbe8aec77 docs: only execute the passport middleware once
Before this change, the session and user context were retrieved once
per HTTP request and not once per session.
2024-01-13 17:56:17 +01:00
..

Example with Passport

This example shows how to retrieve the authentication context from a basic Express + Passport application.

Passport example

Please read the related guide: https://socket.io/how-to/use-with-passport

How to use

$ npm ci && npm start

And point your browser to http://localhost:3000. Optionally, specify a port by supplying the PORT env variable.

How it works

The Socket.IO server retrieves the user context from the session:

function onlyForHandshake(middleware) {
  return (req, res, next) => {
    const isHandshake = req._query.sid === undefined;
    if (isHandshake) {
      middleware(req, res, next);
    } else {
      next();
    }
  };
}

io.engine.use(onlyForHandshake(sessionMiddleware));
io.engine.use(onlyForHandshake(passport.session()));
io.engine.use(
  onlyForHandshake((req, res, next) => {
    if (req.user) {
      next();
    } else {
      res.writeHead(401);
      res.end();
    }
  }),
);