Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io on specific endpoint

I'm learning how to use Socket.io. My website is built on Node.js and express. In this site, I have a number of views. However, I only want to use sockets on one specific view /dashboard/stream. In other words, I only want to turn on sockets if something visits /dashboard/stream. All of the documentation I read implies that I need to configure sockets at the app level in express. In other words, it looks like it's always on. So, if someone uses my website, but never visits /dashboard/stream, sockets would still be running on the server.

Am I missing something? Is there a way to say "if someone visits /dashboard/stream activate sockets for the user?

Thank you for helping me gain clarity on this.

like image 620
user687554 Avatar asked Oct 19 '25 14:10

user687554


1 Answers

The correct way to implement listening on an endpoint is namespaces.

const nsp= io.of('/admin');

nsp.use((socket, next) => {
  // ensure the user has sufficient rights
  next();
});

nsp.on('connection', socket => {
  socket.on('delete user', () => {
    // ...
  });
});

https://socket.io/docs/v3/namespaces/#Custom-namespaces

like image 52
Flecibel Avatar answered Oct 21 '25 03:10

Flecibel