Search code examples
node.jssocket.iochat

Socket.io multiple pages


I'm trying to create a chat using socket.io, I'm having a problem.

I want to know if it is possible to reuse my socket.id in my different pages of my project to not lose the connection of my socket?


Solution

  • A given socket.io connection belongs only to one particular page. When the user browses to a new page (assuming you're not dynamically loading new content into the same master page using a single-page-app (SPA) architecture), that socket.io connection is closed and the new page can then open a new socket.io connection (that will have a different socket.id).

    I want to know if it is possible to reuse my socket.id in my different pages of my project to not lose the connection of my socket?

    No, not when the browser is actually loading a whole new page into the current window/tab.


    The usual way to create some sort of ID that is persistent when you go from one page to the next is to put an ID in a cookie and then that cookie will be available on each new page the user browses to and will stay consistent from one page to the next.

    If you are using express on the server, you can use express-session to automatically create a persistent session for each new user and you can even store data in that session object that will be available on each page the user requests.