Title: Pattern for multiday persistent signalr connection
Tags: javascript;signalr
Question: What is the correct JavaScript pattern to connect to SignalR and maintain the link perpetually while they are on the page, no matter if people hibernate their computers or have spotty internet connections.
The documentation just says use:
$.connection.hub.start()
.done(function(){ console.log('Now connected, connection ID=' + $.connection.hub.id); })
.fail(function(){ console.log('Could not Connect!'); });
But this does not seem to take disconnects and other issues into account.
Also, it doesn't catch the problem of the session expire and requires re-login.
Comment: How is calling an API in a error-handling way an opinion based question?!?

Comment: I have to disagree, he is asking for an answer to a specific issue, that is not a standard implementation of singlar.

Comment: This question is opinion based and is thus off-topic for Stack Overflow.

Comment: *What is the correct JavaScript pattern to connect to SignalR...?* Since there is no single "correct" pattern for connecting to SignalR (hub, persistent connection, etc.), it's a matter of opinion which is "most correct".

Here is the accepted answer: Given that SignalR is a connection based client/server solution, you cannot have expectations of long sustained open connections. So as Kelso Sharp wrote in his answer, the only good thing you can do is manage the events of the connection life cycle.
Check out the documentation for all the life cycle events of a signalR connection:
https://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client#connectionlifetime
So if we do not focus our attention on how to make a persistent connection that never fails, we could instead focus on giving the user an impression of that, by cunningly managing the disconnects, reloads and such in the background.
Here is a diagram showing how I would setup this, even though you do not specify what causes your hub to push data out to clients, but I imaging it could be something like this diagram. The idea here is that you push the same state to some kind of state provider - i.e. cache, web api storage, so that you have the entire set of data available at any given time. When ui loads or disconnects, it should issue a request to this provider to regain state, and then it should reconnect to the hub.
If data consistency is a issue, you could do versioning of the state, keep a local copy in the ui, and then do an audit upon reconnecting. That way you could see if you missed out on something, in which case you would issue catch up requests to the state provider.
To handle the events you just have hook in some functions on your client side:
//this will trigger for all state changes during the connection cycle:
$.connection.hub.stateChanged(function (change) {
if (change.newState === $.signalR.connectionState.reconnecting) {
console.log("liveFeed is reconnecting!");
else if (change.newState === $.signalR.connectionState.connected) {
console.log("liveFeed is connected!");
//this triggers when the disconnecting to the hub.
$.connection.hub.disconnected(function () {
console.log('Connection disconnected')
Comment for this answer: @Cine well you read the documentation all the lifecycle events are listed, you can expect them to trigger when those events occur. With regards to retries and such, there are a couple of patterns you could try out a basic retry pattern with a delay between retries. I would then strongly consider using an increasing delay if the retries fails consecutively. Or you could try the circuit breaker pattern, it is a bit more advanced, and it may not be what you are looking for in this situation.
Comment for this answer: You have any specifics on when `disconnected` is called in relation to `reconnecting`. And is it guaranteed it will always attempt to reconnect until the end of days? If so, what is the delay in attempts? And how could I force an attempt? Also, do you get a notification of the reconnect attempt failing?
Comment for this answer: How to handle the session expire?

Here is another answer: The only way that I that I think this can be done is to use a backplane that stores connection info of each connected client. That said, they will never "Stay Connected" If they lost internet or hibernate, all that you can do is "reconnect"  You will have to store any state information on a continual basis in the event of a disconnection, you cannot do this in the "disconnect" event because by then it is likely too late. One option would be to continually stream state info to a redis cache and periodically send it to that the back plane in more reasonable intervals, or when the disconnected even fires.
Comment for this answer: The goal is not for them to never disconnect, the goal is for the UI to never SEE the disconnect (except in the case if needing to login again). IE when the UI is active and has an inet connection, it is connected.
Comment for this answer: This solution would achieve that I believe, just need to make sure you are managing the UI state, and by doing that you can pull from the redis cache if there is a break in connectivity.
Comment for this answer: right, with the redis cache you always have your current state, so you can make it look like they have never disconnected.

Here is another answer: Figured out how to do the session expire, by wrapping all calls to the server with a retry:
function callServer(call) {
function err(r?: Error) {
var output = $.Deferred();
if (r &amp;&amp;
r.message &amp;&amp;
(r.message.startsWith("Caller is not authorized to invoke the") ||
r.message.startsWith("The user identity cannot change during "))) {
$('#login-dialog')
.one('hide.bs.modal',
() =&gt; {
hub.connection.stop();
$.connection.hub.start()
.then(() =&gt; hub.server.run(call))
.then(output.resolve, output.reject);
})
.modal('show');
return output;
}
// ReSharper disable once SuspiciousThisUsage
return output.rejectWith(this, <any&gt;arguments);
return $.connection.hub.start()
.then(() =&gt; hub.server.run(call))
.then(null, err);
This assumes there is a bootstrap modal dialog #login-dialog that when closed means it has handled re-login.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 3, 'CommentCount': 4, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2016:00:10/21/16', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><signalr>', 'Title': 'Pattern for multiday persistent signalr connection', 'ViewCount': 473, 'id': 40172346, 'user_AboutMe': '', 'user_AccountId': 97309.0, 'user_DisplayName': 'Cine', 'user_Reputation': 4097.0, 'user_Views': 307.0, 'user_id': 264022.0}}