npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

easy-server-sent-events

v1.0.14

Published

An easy to use Server Side Events library for Node.js + frontend

Downloads

9

Readme

easy-server-sent-events

An easy to use Server Side Events library for Express/Node.js + a frontend-library for web browsers.

Automatically resumes broken connections, provides broadcasting capabilities and simplifies the syntax on both backend and frontend.

Installation

npm install easy-server-sent-events

Backend

Here's an example of how to use the module on the backend in Node.js:

  • It is Express middleware, so you'll have to use express.
  • You don't have to use express-session but it makes it much easier, when you want to target the sending of events to specific clients.
const express = require('express');
const session = require('express-session');
const app = express();
const sse = require('easy-server-sent-events');

// express-session middleware 
// ALWAYS APPLY FIRST OF ALL MIDDLEWARE!
// (Please note: It might be better to store sessions in a db)
app.use(session({
  secret: 'something hard to guess',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false }
}));

// You can change the following options:
// endpoint: which endpoint you want to use
// script: at which route a clientside library should be served
// These are the default values (they will be set even if omitted):
const options = {
  endpoint: '/api/sse',
  script: '/sse.js'
};

// Calling the module returns an object with four properties:
// SSE:
//     the middleware - use with an express app
// send: 
//     a function that sends events from the server:
//     send(to, eventType, data)
// openSessions: 
//     a function returns how many sessions are open
// openConnections: 
//     a function that returns how man connections that are open
const {SSE, send, openSessions, openConnections} = sse(options);
app.use(SSE);

// Other middleware goes here
// For example static middleware (if needed)
app.use(express.static('www'));

// Start web server
app.listen(4000, () => console.log('Listening on port 4000'));

// Example of using send(to, eventType, data)
// Here we send messages to all connected clients
// We randomly choose between the event types
// 'message' and 'other' (you can name your event types how you like)
// and send a message (an object with the properties cool and content)
function test() {
  send(
    'all',
    Math.random() < .5 ? 'message' : 'other',
    { 
      cool: true, 
      content: 'This is a message sent ' + new Date().toLocaleTimeString() 
    }
  );
  // log how many openSessions and openConnections we have
  console.log(
    'openSessions', openSessions(),
    'openConnections', openConnections()
  );
}

// send an event every 3 seconds
setInterval(test, 3000);

How do I send events to specific clients?

  • You send events to specific clients by replacing the "all" value with a filter.
  • The filter receives the request object originally sent from the client.
  • Thus - if you use the express-session middleware you will have a session object attached to the request object.
Filter by session properties

The following will only send messages to a user with the username 'root':

send(
  req => req.session.user && req.session.user.username === 'root', 
  'superSecret',
  'This is a super secret message.'
);
Alternate ways to filter

If you decide to not use express-session the property req.query.browserId could be handy for identifying different clients. It is set by this module and unique for each client.

Frontend

No build system/vanilla JS

If you are using this module without a build system that handles import statements you can include the frontend library with a script tag:

<script src="/sse.js"></script>

With a build system (with React, Vue etc)

In build systems that support import statements use:

import SSE from 'easy-server-sent-events/sse';

Basic usage

Create a new instance of the library and add eventlisteners

// Create an instance
// a connect it to the endpoint
// '/api/sse' (default)
const sse = new SSE('/api/sse');

sse.listen('message', (data) => {
  console.log('message', data);
});

sse.listen('other', (data) => {
  console.log('other', data);
});

Restart after login/logout etc

After login/logout and other events in your application that might change the session object on the backend, immediately restart your instance to make sure it has access to these changes:

sse.restart();

Remove an event listener

If you want to remove and event listener you can save the result of a call to listen in a variable and call unlisten later:

const sse = new SSE('/api/sse');

let messageListener = sse.listen('message', (data) => {
  console.log('message', data);
});

// later...
sse.unlisten(messageListener);

Usage with the create-react-app dev server: Proxying

Proxying SSE (as well as web sockets) is hard/not doable with the built in proxy system in create-react-app.

We recommend that you use the npm package react-amazing proxy that solves all problems with letting SSE through the proxy.

Older browsers

Microsoft Edge and Microsoft IE does not support server sent events because of lack of support for the EventSource object. There is a polyfill available:
event-source-polyfill.