Skip to content

feat(headers): allow headers to be defined as a function to return dynamic values#67

Open
whawker wants to merge 1 commit into
Azure:mainfrom
whawker:headers-as-function
Open

feat(headers): allow headers to be defined as a function to return dynamic values#67
whawker wants to merge 1 commit into
Azure:mainfrom
whawker:headers-as-function

Conversation

@whawker

@whawker whawker commented Jan 5, 2024

Copy link
Copy Markdown

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]);

@whawker

whawker commented Jan 5, 2024

Copy link
Copy Markdown
Author

@microsoft-github-policy-service agree

@dngconsulting

Copy link
Copy Markdown

What about this PR ?

@alex-w0

alex-w0 commented Nov 29, 2024

Copy link
Copy Markdown

Is this project still maintained? I need this feature

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants