fetch-event-source icon indicating copy to clipboard operation
fetch-event-source copied to clipboard

Avoid stale headers by supplying them as a function

Open inad9300 opened this issue 2 years ago • 2 comments
trafficstars

One of the most common usages for headers is authentication. However, if one provides a token as part of a header to this library, its value will remain the same forever, even through retries and whatnot. If at a given moment the token expires and needs to be refreshed, there will be no hope in reconnecting, so the retry mechanism becomes quite pointless.

I propose to allow passing "headers" in as a function, in which case it will be called every time fetch() is, in order to recompute the potential dynamic values in them.

inad9300 avatar Mar 08 '23 09:03 inad9300

For anyone in need of a workaround, if you check for 401 in onopen, something like:

if (response.status === 401) {
  throw new AuthenticationError();
}

you can catch that outside of the fetchEventSource-call, get a fresh token, and then call fetchEventSource again.

Something like:

setUpConnection()
  .catch(err) {
      if (err instanceof AuthenticationError) {
        // Try again with a new token
        setUpConnection();

where setUpConnection grabs a token and then calls fetchEventSource.

jgarplind avatar Apr 21 '23 06:04 jgarplind

I've added a headers as a function PR here https://github.com/Azure/fetch-event-source/pull/67 FWIW

whawker avatar Jan 12 '24 09:01 whawker