Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
@microsoft/fetch-event-source
Advanced tools
A better API for making Event Source requests, with all the features of fetch()
@microsoft/fetch-event-source is a JavaScript library that provides a simple way to handle Server-Sent Events (SSE) using the Fetch API. It allows you to receive real-time updates from a server over an HTTP connection.
Basic Event Source
This feature allows you to connect to an SSE endpoint and handle incoming messages. The `onmessage` callback is triggered whenever a new message is received, and the `onerror` callback handles any errors.
const { fetchEventSource } = require('@microsoft/fetch-event-source');
fetchEventSource('https://example.com/sse', {
onmessage(event) {
console.log('New message:', event.data);
},
onerror(err) {
console.error('Error:', err);
}
});
Custom Headers
This feature allows you to include custom headers in your SSE request. This is useful for scenarios where you need to pass authentication tokens or other custom headers.
const { fetchEventSource } = require('@microsoft/fetch-event-source');
fetchEventSource('https://example.com/sse', {
headers: {
'Authorization': 'Bearer YOUR_TOKEN'
},
onmessage(event) {
console.log('New message:', event.data);
},
onerror(err) {
console.error('Error:', err);
}
});
Reconnection Logic
This feature demonstrates how to implement reconnection logic when the SSE connection is closed. The `onclose` callback is used to attempt reconnection after a specified delay.
const { fetchEventSource } = require('@microsoft/fetch-event-source');
fetchEventSource('https://example.com/sse', {
onmessage(event) {
console.log('New message:', event.data);
},
onerror(err) {
console.error('Error:', err);
},
onclose() {
console.log('Connection closed, attempting to reconnect...');
setTimeout(() => {
fetchEventSource('https://example.com/sse', options);
}, 5000);
}
});
The `eventsource` package is a polyfill for the EventSource API, which is used to receive server-sent events. It provides a similar interface to the native EventSource but can be used in environments where the native implementation is not available. Compared to @microsoft/fetch-event-source, it does not use the Fetch API and may have different performance characteristics.
The `sse.js` package is a lightweight library for handling server-sent events. It provides a simple interface for connecting to SSE endpoints and handling messages. While it offers similar functionality to @microsoft/fetch-event-source, it may not have as many features or customization options.
The `reconnecting-eventsource` package is an extension of the EventSource API that adds automatic reconnection capabilities. It is designed to handle network interruptions and automatically reconnect to the SSE endpoint. This package is similar to @microsoft/fetch-event-source in terms of reconnection logic but does not use the Fetch API.
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:
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:
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.)
npm install @microsoft/fetch-event-source
// BEFORE:
const sse = new EventSource('/api/sse');
sse.onmessage = (ev) => {
console.log(ev.data);
};
// AFTER:
import { fetchEventSource } from '@microsoft/fetch-event-source';
await fetchEventSource('/api/sse', {
onmessage(ev) {
console.log(ev.data);
}
});
You can pass in all the other parameters exposed by the default fetch API, for example:
const ctrl = new AbortController();
fetchEventSource('/api/sse', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
foo: 'bar'
}),
signal: ctrl.signal,
});
You can add better error handling, for example:
class RetriableError extends Error { }
class FatalError extends Error { }
fetchEventSource('/api/sse', {
async onopen(response) {
if (response.ok && response.headers.get('content-type') === EventStreamContentType) {
return; // everything's good
} else if (response.status >= 400 && response.status < 500 && response.status !== 429) {
// client-side errors are usually non-retriable:
throw new FatalError();
} else {
throw new RetriableError();
}
},
onmessage(msg) {
// if the server emits an error message, throw an exception
// so it gets handled by the onerror callback below:
if (msg.event === 'FatalError') {
throw new FatalError(msg.data);
}
},
onclose() {
// if the server closes the connection unexpectedly, retry:
throw new RetriableError();
},
onerror(err) {
if (err instanceof FatalError) {
throw err; // rethrow to stop the operation
} else {
// do nothing to automatically retry. You can also
// return a specific retry interval here.
}
}
});
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:
require('fast-text-encoding');
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.
2.0.0
This release improves the performance of parsing the response stream and fixes some corner cases to better match the spec.
The id
, event
, and data
fields are now initialized to empty strings, per the spec (they were previously undefined
)
The onmessage
callback is now called for all messages (it was previously triggered only for messages with a data
field)
If a message contains multiple data
fields, they will be concatenated together into a single string. For example, the following message:
data: Foo
data:Bar
data
data: Baz
will result in { data: 'Foo\nBar\n\nBaz' }
If the server sends an id
field with an empty value, the last-event-id header will no longer be sent on the next reconnect.
parseStream
function has been removed. The parse implementation was previously based on async generators, which required a lot of supporting code in both the typescript-generated polyfill as well as the javascript engine. The new implementation is based on simple callbacks, which should be much faster.FAQs
A better API for making Event Source requests, with all the features of fetch()
The npm package @microsoft/fetch-event-source receives a total of 379,310 weekly downloads. As such, @microsoft/fetch-event-source popularity was classified as popular.
We found that @microsoft/fetch-event-source demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 5 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.