fetch-event-source
fetch-event-source copied to clipboard
feat(headers): allow headers to be defined as a function to return dynamic values
trafficstars
I am using this library as a means to provide a JWT bearer token via the Authorization header to my event source endpoint.
However I have found that when the connection is retried (either explicitly, or via the page visibility API), it reuses the headers that were first passed to fetchEventSource.
In my use case, as bearer tokens are short lived, the retry uses a stale bearer token and the retry call fails as unauthorised.
This PR adds the ability to pass headers as a function, meaning you can pass dynamic values, such as an up-to-date bearer token. It is also backwards compatible with the existing behaviour.
Example (using React)
const getAccessToken = useAccessToken();
useEffect(() => {
fetchEventSource(endpoint, {
headers: () => ({
Authorization: `Bearer ${getAccessToken()}`,
Accept: 'application/json',
}),
// etc
})
}, [getAccessToken]);
@microsoft-github-policy-service agree