Installations
npm install @quantum-boost/fetch-event-source
Developer Guide
Typescript
Yes
Module System
ESM
Min. Node Version
>=16.15
Node Version
16.16.0
NPM Version
8.11.0
Score
73
Supply Chain
99.4
Quality
75.2
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Unable to fetch Contributors
Languages
TypeScript (100%)
Developer
Azure
Download Statistics
Total Downloads
419
Last Day
1
Last Week
2
Last Month
7
Last Year
50
GitHub Statistics
1,936 Stars
20 Commits
148 Forks
37 Watching
1 Branches
10,000 Contributors
Bundle Size
3.36 kB
Minified
1.59 kB
Minified + Gzipped
Package Meta Information
Latest Version
3.0.0
Package Id
@quantum-boost/fetch-event-source@3.0.0
Unpacked Size
64.70 kB
Size
12.43 kB
File Count
26
NPM Version
8.11.0
Node Version
16.16.0
Publised On
11 Apr 2023
Total Downloads
Cumulative downloads
Total Downloads
419
Last day
0%
1
Compared to previous day
Last week
0%
2
Compared to previous week
Last month
250%
7
Compared to previous month
Last year
-86.4%
50
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dev Dependencies
7
Fetch Event Source
This package provides a better API for making Event Source requests - also known as server-sent events - with all the features available in the Fetch API.
The default browser EventSource API imposes several restrictions on the type of request you're allowed to make: the only parameters you're allowed to pass in are the url
and withCredentials
, so:
- You cannot pass in a request body: you have to encode all the information necessary to execute the request inside the URL, which is limited to 2000 characters in most browsers.
- You cannot pass in custom request headers
- You can only make GET requests - there is no way to specify another method.
- If the connection is cut, you don't have any control over the retry strategy: the browser will silently retry for you a few times and then stop, which is not good enough for any sort of robust application.
This library provides an alternate interface for consuming server-sent events, based on the Fetch API. It is fully compatible with the Event Stream format, so if you already have a server emitting these events, you can consume it just like before. However, you now have greater control over the request and response so:
- You can use any request method/headers/body, plus all the other functionality exposed by fetch(). You can even provide an alternate fetch() implementation, if the default browser implementation doesn't work for you.
- You have access to the response object if you want to do some custom validation/processing before parsing the event source. This is useful in case you have API gateways (like nginx) in front of your application server: if the gateway returns an error, you might want to handle it correctly.
- If the connection gets cut or an error occurs, you have full control over the retry strategy.
In addition, this library also plugs into the browser's Page Visibility API so the connection closes if the document is hidden (e.g., the user minimizes the window), and automatically retries with the last event ID when it becomes visible again. This reduces the load on your server by not having open connections unnecessarily (but you can opt out of this behavior if you want.)
Install
1npm install @microsoft/fetch-event-source
Usage
1// BEFORE: 2const sse = new EventSource('/api/sse'); 3sse.onmessage = (ev) => { 4 console.log(ev.data); 5}; 6 7// AFTER: 8import { fetchEventSource } from '@microsoft/fetch-event-source'; 9 10await fetchEventSource('/api/sse', { 11 onmessage(ev) { 12 console.log(ev.data); 13 } 14});
You can pass in all the other parameters exposed by the default fetch API, for example:
1const ctrl = new AbortController();
2fetchEventSource('/api/sse', {
3 method: 'POST',
4 headers: {
5 'Content-Type': 'application/json',
6 },
7 body: JSON.stringify({
8 foo: 'bar'
9 }),
10 signal: ctrl.signal,
11});
You can add better error handling, for example:
1class RetriableError extends Error { } 2class FatalError extends Error { } 3 4fetchEventSource('/api/sse', { 5 async onopen(response) { 6 if (response.ok && response.headers.get('content-type') === EventStreamContentType) { 7 return; // everything's good 8 } else if (response.status >= 400 && response.status < 500 && response.status !== 429) { 9 // client-side errors are usually non-retriable: 10 throw new FatalError(); 11 } else { 12 throw new RetriableError(); 13 } 14 }, 15 onmessage(msg) { 16 // if the server emits an error message, throw an exception 17 // so it gets handled by the onerror callback below: 18 if (msg.event === 'FatalError') { 19 throw new FatalError(msg.data); 20 } 21 }, 22 onclose() { 23 // if the server closes the connection unexpectedly, retry: 24 throw new RetriableError(); 25 }, 26 onerror(err) { 27 if (err instanceof FatalError) { 28 throw err; // rethrow to stop the operation 29 } else { 30 // do nothing to automatically retry. You can also 31 // return a specific retry interval here. 32 } 33 } 34});
Compatibility
This library is written in typescript and targets ES2017 features supported by all evergreen browsers (Chrome, Firefox, Safari, Edge.) You might need to polyfill TextDecoder for old Edge (versions < 79), though:
1require('fast-text-encoding');
Contributing
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.
When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
security policy file detected
Details
- Info: security policy file detected: SECURITY.md:1
- Info: Found linked content: SECURITY.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: SECURITY.md:1
- Info: Found text in security policy: SECURITY.md:1
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
0 existing vulnerabilities detected
Reason
dependency not pinned by hash detected -- score normalized to 3
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:22: update your workflow using https://app.stepsecurity.io/secureworkflow/Azure/fetch-event-source/node.js.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:24: update your workflow using https://app.stepsecurity.io/secureworkflow/Azure/fetch-event-source/node.js.yml/main?enable=pin
- Info: 0 out of 2 GitHub-owned GitHubAction dependencies pinned
- Info: 1 out of 1 npmCommand dependencies pinned
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
Found 1/19 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/node.js.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'main'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 2 are checked with a SAST tool
Score
4.2
/10
Last Scanned on 2025-02-03
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More