EventSource
EventSource copied to clipboard
Reconnect with new Header
Halo, I have a jwt token implementation (firebase auth) but when token expired, the lib not refreshing the token.
hm.. should it just use the same object to get the headers? I think, the chance, that this will be standard behavior of native EventSource could be low.
we need a different for this. may be it can be resolved if the polyfill support function as headers
could you update headers during the "error" event instead?
could you update headers during the "error" event instead?
What do you mean? can we update the instantiated EventSourcePolyfill header?
Or just recreate one with the new header at each error?
@Yaffle The most common authentication uses access token to be sent in header (supported) but when it expires, the server middleware returns 401. In such case, we need to use refresh token, get new access token and reconnect. For https client, this is done in http interceptor. How can we implement such mechanism using event source? Thank you very much!
@zencakd you can use something like this:
function connect() {
var es = new EventSource('https://wikipedia.org');
es.onerror = function (event) {
if (es.readyState === EventSource.CLOSED) {
// check if old token is old here, request a new token,
window.setTimeout(function() {
connect();
}, 0);
}
};
es.onmessage = function (event) {
console.log(event.data);
};
}
I think, with the native EventSource only something like this is possible. Do you have better ideas of how it can look like?
@Yaffle The best way would be to get the error code and get the new token only if the error code is 401. If the connection is closed (EventSource.CLOSED), we only need to reconnect but the access token can be still valid at that time. Yes, native EventSource does not offer more as well. Thank you for prompt reaction!
@zencakd , the polyfill exposes the error code - check event.status
in the error event handler
@Yaffle Oh, thank you!
You should keep the connexion Always alive by sending from your back an empty msg every 30s.
And manage the 401 error by closing the eventsource and reopen it with the good token
@zakariafadili I got it, thank you!
@Yaffle, maybe a "before reconnect" event would be a good idea
@SrMouraSilva will the event handler use promises?
Hi, I'm facing the same issue with the necessity to update a JWT token used in the authorization headers. By the way from this ticket, the solution is not clear to me. Do you have further details on how to tackle such a case? Thank you in advance
You could try this for now: const es = new EventSource(...); es.headers['JWT'] = value; but of course, this may not work in the future
yep it's quite weak. I think I'll come up with some custom logic to re-instantiate the ES when the token gets updated but indeed a native solution would be nice to have :D Thank you for your help though!