简体   繁体   中英

How to make persistent web socket connection across page refresh in a secure way in ReactJS?

I am using web socket for communicating with back end server from a reactjs client. Socket is getting closed when a user refreshes the page. That is happening as expected. However, my requirement is to have persistent web socket connection across page refresh. I am currently using localstorage to store access, refresh tokens.

I understand this is not a secure way to resolve the problem. I want to know if there is any secure way available to achieve my goal.

I am not sure if this works because it would be kind of a security breach to be able to let the user connected even though he is not on your page. (Because as you are refreshing, you leave the page and re-enter it).

Your best bet maybe something with a service worker that can run in the background :)

Since you are using Web Sockets it would be a good idea to use a SharedWorker to create a new thread for your Web Sockets. The difference between a normal WebWorker and a SharedWorker is that the web worker will create a new session in each tab or browser when loading the page, whereas the shared worker will use the same session in each tab. So all of your tabs or windows will have the same worker and same Web Socket connection to work with.

I quoted from this answer which will probably point you to the right direction: https://stackoverflow.com/a/61866896/11665341

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM