Security News
38% of CISOs Fear They’re Not Moving Fast Enough on AI
CISOs are racing to adopt AI for cybersecurity, but hurdles in budgets and governance may leave some falling behind in the fight against cyber threats.
eventsource
Advanced tools
The eventsource npm package is a Node.js implementation of the EventSource client, which is used for receiving server-sent events (SSE). It allows clients to subscribe to a stream of updates from a server over an HTTP connection. The package is designed to be compliant with the W3C EventSource specification and is typically used for real-time data feeds, such as live notifications, stock prices updates, or any other continuous data stream.
Connecting to an SSE server
This code demonstrates how to connect to an SSE server and listen for messages. The 'onmessage' handler is called whenever a new message is received, and the 'onerror' handler is called if there's an error with the connection.
const EventSource = require('eventsource');
const es = new EventSource('http://example.com/events');
es.onmessage = function(event) {
console.log(event.data);
};
es.onerror = function(err) {
console.error('EventSource failed:', err);
};
Listening for specific event types
This code snippet shows how to listen for specific event types using the 'addEventListener' method. In this example, the client listens for 'userupdate' events and processes the received data.
const EventSource = require('eventsource');
const es = new EventSource('http://example.com/events');
es.addEventListener('userupdate', function(event) {
const userData = JSON.parse(event.data);
console.log('User update:', userData);
});
Reconnecting after connection loss
This example illustrates the automatic reconnection feature of the EventSource API. The 'onopen' handler is called when the connection is successfully established, and the 'onerror' handler indicates that the connection has been lost and a reconnection attempt will be made.
const EventSource = require('eventsource');
const es = new EventSource('http://example.com/events');
es.onopen = function() {
console.log('Connection to server opened.');
};
es.onerror = function() {
console.log('Connection lost, the browser will automatically attempt to reconnect.');
};
The sse-client package is another implementation of the EventSource API for Node.js. It provides similar functionality for connecting to SSE servers and handling server-sent events. Compared to eventsource, it may have different API nuances or additional features, but the core functionality remains the same.
Oceanwind is not a direct alternative to eventsource, but it is an example of a package that uses server-sent events to provide real-time updates to clients. It is a library for managing real-time communication between servers and clients, and it may include an SSE implementation as part of its feature set.
WhatWG/W3C-compatible server-sent events/eventsource client. The module attempts to implement an absolute minimal amount of features/changes beyond the specification.
If you're looking for a modern alternative with a less constrained API, check out the eventsource-client
package.
npm install --save eventsource
Basically, any environment that supports:
If you need to support older runtimes, try the 2.x
branch/version range (note: 2.x branch is primarily targetted at Node.js, not browsers).
import {EventSource} from 'eventsource'
const es = new EventSource('https://my-server.com/sse')
/*
* This will listen for events with the field `event: notice`.
*/
es.addEventListener('notice', (event) => {
console.log(event.data)
})
/*
* This will listen for events with the field `event: update`.
*/
es.addEventListener('update', (event) => {
console.log(event.data)
})
/*
* The event "message" is a special case, as it will capture events _without_ an
* event field, as well as events that have the specific type `event: message`.
* It will not trigger on any other event type.
*/
es.addEventListener('message', (event) => {
console.log(event.data)
})
/**
* To explicitly close the connection, call the `close` method.
* This will prevent any reconnection from happening.
*/
setTimeout(() => {
es.close()
}, 10_000)
Make sure you have configured your TSConfig so it matches the environment you are targetting. If you are targetting browsers, this would be dom
:
{
"compilerOptions": {
"lib": ["dom"],
},
}
If you're using Node.js, ensure you have @types/node
installed (and it is version 18 or higher). Cloudflare workers have @cloudflare/workers-types
etc.
The following errors are caused by targetting an environment that does not have the necessary types available:
error TS2304: Cannot find name 'Event'.
error TS2304: Cannot find name 'EventTarget'.
error TS2304: Cannot find name 'MessageEvent'.
See MIGRATION.md for a detailed migration guide.
The error
event has a message
and code
property that can be used to get more information about the error. In the specification, the Event
es.addEventListener('error', (err) => {
if (err.code === 401 || err.code === 403) {
console.log('not authorized')
}
})
fetch
implementationThe EventSource
constructor accepts an optional fetch
property in the second argument that can be used to specify the fetch
implementation to use.
This can be useful in environments where the global fetch
function is not available - but it can also be used to alter the request/response behaviour.
const es = new EventSource('https://my-server.com/sse', {
fetch: (input, init) =>
fetch(input, {
...init,
headers: {
...init.headers,
Authorization: 'Bearer myToken',
},
}),
})
Use a package like node-fetch-native
to add proxy support, either through environment variables or explicit configuration.
// npm install node-fetch-native --save
import {fetch} from 'node-fetch-native/proxy'
const es = new EventSource('https://my-server.com/sse', {
fetch: (input, init) => fetch(input, init),
})
Use a package like undici
for more control of fetch options through the use of an Agent
.
// npm install undici --save
import {fetch, Agent} from 'undici'
await fetch('https://my-server.com/sse', {
dispatcher: new Agent({
connect: {
rejectUnauthorized: false,
},
}),
})
MIT-licensed. See LICENSE.
FAQs
WhatWG/W3C compliant EventSource client for Node.js and browsers
We found that eventsource demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 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
CISOs are racing to adopt AI for cybersecurity, but hurdles in budgets and governance may leave some falling behind in the fight against cyber threats.
Research
Security News
Socket researchers uncovered a backdoored typosquat of BoltDB in the Go ecosystem, exploiting Go Module Proxy caching to persist undetected for years.
Security News
Company News
Socket is joining TC54 to help develop standards for software supply chain security, contributing to the evolution of SBOMs, CycloneDX, and Package URL specifications.