Skip to content

Instantly share code, notes, and snippets.

@naoki-sawada
Last active April 5, 2024 01:49
Show Gist options
  • Star 41 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save naoki-sawada/2f4e135feb3c6bad7f555f59dfb40020 to your computer and use it in GitHub Desktop.
Save naoki-sawada/2f4e135feb3c6bad7f555f59dfb40020 to your computer and use it in GitHub Desktop.
Simple socket.io room and auth example
const io = require('socket.io-client');
const socket = io('http://localhost:3000', {
transportOptions: {
polling: {
extraHeaders: {
'Authorization': 'Bearer abc',
},
},
},
});
socket.on('connect', () => {
console.log('connected!');
socket.emit('room', 'room1');
});
socket.on('message', data => {
console.log(data);
});
const server = require('http').createServer();
const io = require('socket.io')(server);
const isValidJwt = (header) => {
const token = header.split(' ')[1];
if (token === 'abc') {
return true;
} else {
return false;
}
};
// io.of('/test');
io.use((socket, next) => {
const header = socket.handshake.headers['authorization'];
console.log(header);
if (isValidJwt(header)) {
return next();
}
return next(new Error('authentication error'));
});
io.on('connection', (socket) => {
socket.on('room', room => {
console.log(room);
socket.join(room);
});
});
setInterval(() => {
io.sockets.to('room1').emit('message', 'what is going on, party people?');
}, 3000);
setInterval(() => {
io.sockets.to('room2').emit('message', 'anyone in this room yet?');
}, 3000);
server.listen(3000);
@nitko12
Copy link

nitko12 commented Mar 15, 2020

Thank you, exactly what I needed!

@andrevbnk
Copy link

<3 thx

@ardaorkin
Copy link

Thank you! It is very helpful.

@fabiorvs
Copy link

Thank you, perfect.

@shov
Copy link

shov commented Oct 26, 2021

Handle Auth for a namespace and go further with connection

Client
(https://cdn.socket.io/4.3.2/socket.io.min.js)

const socket = io.connect(
    `${domain}/api/v1/xxx/42`,
    {
        auth: {
            "authorization": `303338ce-d71e-4304-abd2-3cfc40a1589a303338ce-d71e-4304-abd2-3cfc40a1589a`,
        },
        transports: ['websocket', 'polling'],
    }
)
socket.on("connect", () => {
    console.log('conected:', socket.id) 
})

Server
this._authMiddleware.action here is a custom async express middleware you probably are using in other part of your project

this._io
  .of(/^\/api\/v1\/xxx\/(?<id>\d+)$/)
  .use((socket: Socket, next) => {
      const reqStub = {headers: socket.handshake.auth, user: null}
      this._authMiddleware.action(reqStub, {}, (e: any) => {
          if (e) {
              next(e)
              return
          }
  
          (socket.request as unknown as {user: string}).user = reqStub.user!
          next()
      }).catch(e => {
          next(e)
      })
  })
  .on('connection', (socket: Socket) => {
      socket.emit('msg', `Hello ${(socket.request as unknown as {user: string}).user}`)
  })

@neody
Copy link

neody commented Dec 22, 2021

console.log('shark eats seafood');
console.log('Thank you fery mut');

@markosole
Copy link

Fantastic, short, clean and simple. More importat: works

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment