Reputation: 379
I have a web site in which I'd like to have a user system where the user is logged in no matter where he is on the web site.
Using socket.io, I found that each HTML page requires its own socket.io connection. So every time a user leaves one HTML page for another, he will disconnect the first socket and connect the other.
What is the best way to preserve such a connection? I don't want the user to manually log in on every HTML page. I'd assume that passing the login data as HTML parameters and automatically log in to the server with those parameters is extremely dumb, but currently it is the only solution I can think of.
Ideally, socket.io would use the same socket on the entire site.
I assume that I'm missing something though, considering that all websites with a user system has the desired functionality.
Upvotes: 1
Views: 110
Reputation: 19569
Two things are important here:
If you leave the page, you disconnect. Period. You cannot change that, and if your pages are distinct, your sockets will get reconnected each time. One way to work around this problem would be to create instead a SPA - single page application with a framework like angular or ember. It's basically client side routing - catch your clicks and show different "pages" without reloading. In addition to keeping the socket open, you also get the benefit of not having to reload all the shared assets, network overhead etc, which is extra beneficial on mobile devices.
But you don't have to.
As others have suggested, your actual problem is that your auth mechanism isn't doing enough. Even if your socket gets reset, your new socket needs to be re-authenticated. There are libraries that can do the work, or do it yourself. It can be something simple like picking up cookie or some sort of an auth token that you got on your first auth you send with your socket connect (if it's present). And then authentication is done against this value.
With auth set up like that, you can share auth between regular and socket calls and you stay authenticated on all pages and page reloads.
Upvotes: 1