Lightweight, fast and framework-agnostic sse service for NodeJS

Overview

SSE service

Lightweight, fast and framework-agnostic sse service for NodeJS

Written on TS.

Features

  • Could be embedded to Express, Fastify, Nest, etc. implemantation
  • Easy to manage connections by providing a groups feature of user conections
  • Allows a few connections per user (from different devices for example), so you can send data to every user connection providing the user id
  • Allows to pass through original response headers(headers that were added by your framework, for example) to end up response stream

Basic usages examples

Fastify

import { SSEClientObjInterface } from 'sse-service';
import { fastify } from 'fastify';

const server = fastify({ logger: true });

server.route({
  method: 'GET',
  url: '/sse',
  handler: async (req, res) => {
    sse.connectSSE({
      clientId: 'unique id', // this is a primary key of how your client connection could be retrieved, could be ommited, library will take care of creating unique id  
      // client id could be retrieved from the JWT token for example
      req: req.raw, // here we link to raw NodeJS request object, because its wrapped by Fastify
      res: res.raw, // the same as for request
      originalResHeaders: res.getHeaders(), // sometimes you need to pass through response headers added by Fastify, this headers will be added to raw NodeJS response stream
      onDisconnectCb: () => {
        // ....
      }, // sometimes you need to perform some actions when user disconnects
    });
  },
});

Then you can use it like this in some service where you receive updates from the db for example:

// someService.ts

import { sendSSEToClient } from 'sse-service';

// ....

// some function that handles update from DB or whatever
const processUpdate = (update) => {
  const { userId, ...payload } = update;
  
  sendSSEToClient(userId, payload); // this will send payload to every connection that user with userId has
  
  // OR send update to all:

  sendSSEToAll(payload);
}; 

Nest

Take a note that Nest has built-in SSE implementation: https://docs.nestjs.com/techniques/server-sent-events

So maybe for you goals it will be enough using it

// sse.controller.ts

import { connectSSE } from 'sse-service';

// ...

export class SseController {

    // ...
  
    public sse(@Req() req, @Res() res) {
      connectSSE({
        clientId: req.user.id, // this is a primary key of how your client connection could be retrieved, could be ommited, library will take care of creating unique id  
        // client id could be retrieved from the JWT token for example
        req,
        res,
        originalResHeaders: res.getHeaders(), // sometimes you need to pass through response headers added by Nest (actually it is Fastify or Express under the hood), this headers will be added to raw NodeJS response stream
        onDisconnectCb: () => {
          // ... 
        }, // sometimes you need to perform some actions when user disconnects
      });
    }
}

Then you can use it like this in some service where you receive updates from the db for example:

// someService.ts

import { sendSSEToClient } from 'sse-service';

// ....

// some function that handles update from DB or whatever
const processUpdate = (update) => {
  const { userId, ...payload } = update;
  
  sendSSEToClient(userId, payload); // this will send payload to every connection that user with userId has

  // OR send update to all:

  sendSSEToAll(payload);
}; 

Express

var express = require('express')
var app = express()

app.get('/sse', function (req, res) {
  connectSSE({
    clientId: req.user.id, // this is a primary key of how your client connection could be retrieved, could be ommited, library will take care of creating unique id  
    // client id could be retrieved from the JWT token for example
    req,
    res,
    originalResHeaders: res.getHeaders(), // sometimes you need to pass through response headers added by Express, this headers will be added to raw NodeJS response stream
    onDisconnectCb: () => {
      // ... 
    }, // sometimes you need to perform some actions when user disconnects
  });
})

app.listen(3000);

Then you can use it like this in some service where you receive updates from the db for example:

// someService.ts

import { sendSSEToClient } from 'sse-service';

// ....

// some function that handles update from DB or whatever
const processUpdate = (update) => {
  const { userId, ...payload } = update;
  
  sendSSEToClient(userId, payload); // this will send payload to every connection that user with userId has

  // OR send update to all:

  sendSSEToAll(payload);
}; 

Installation

npm install sse-service

API

connectSSE(params)

Setups SSE connection

params:


{
  req: HttpRequest; // NodeJS raw request object
  
  res: HttpResponse; // NodeJS raw response object
  
  originalResHeaders: HttpResponseHeaders; // response headers from the response object of you framework,
  // for example Fastify wraps original response object and could add additional headers,
  // so if you want to pass them through call .getHeaders() on the framework's response object and pass here 
  
  meta?: Record<string, any>; // any metadata to be persisted in client object that will be created 
  
  clientId?: string; // this is a primary key of how your client connection could be retrieved, 
  // could be ommited, library will take care of creating unique id  
  // client id could be retrieved from the JWT token for example
  
  onDisconnectCb?: () => void; // sometimes you need to perform some actions when user disconnects
  
  groupName?: string; // this param allows you to add this user connection to some specific group(namespace)
  // so later you could send a SSE message for all users connections from this group
  // by default all connections being added to default group name
}

Method returns:


 {
    client: {
        connections: HttpResponse[]; // array of raw NodeJS responses, 
        // will contain more then one if we add few connections by the same clientId param
        meta?: Record<string, any>; // any meta you have added by meta param
        clientId: string; // client id you passed to or the one generated by lib
    };
    currConnection: HttpResponse // raw NodeJS response object that was esatablished by this specific connectSSE method call 
 }
 

sendSSEToClient(clientId, msg [, eventType [, groupName [, sseMsgId ] ] ])

Send message to specific client by id

Params:

Param Type/Required Comment
clientId Type: string
Required: true
Id of the client you want send message to
msg Type: string or Record<string, any> or any[]
Required: true
Message to send
eventType Type: string
Required: false
Event type param in SSE message, check: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
groupName Type: string
Required: false
The group(namespace) where to get this client by id from, if not provided it goes to default group
sseMsgId Type: number
Required: false
The event ID to set the EventSource object's last event ID value, check: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

sendSSEToConnection(connection, msg [, eventType [, sseMsgId ] ])

Send message to specific connection

Params:

Param Type/Required Comment
connection Type: HttpResponse
Required: true
Response object that was established for SSE
msg Type: string or Record<string, any> or any[]
Required: true
Message to send
eventType Type: string
Required: false
Event type param in SSE message, check: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
sseMsgId Type: number
Required: false
The event ID to set the EventSource object's last event ID value, check: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

sendSSEToAll(connection, msg [, eventType [, sseMsgId ] ])

Send message to all active clients

Params:

Param Type/Required Comment
msg Type: string or Record<string, any> or any[]
Required: true
Message to send
eventType Type: string
Required: false
Event type param in SSE message, check: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
groupName Type: string
Required: false
The group(namespace) where to get this client by id from, if not provided it goes to default group
sseMsgId Type: number
Required: false
The event ID to set the EventSource object's last event ID value, check: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

getClientObj(clientId [, groupName ])

Get user's active connections and his meta

Params:

Param Type/Required Comment
clientId Type: string
Required: true
Message to send
groupName Type: string
Required: false
The group(namespace) where to get this client by id from, if not provided it goes to default group

Method returns:

 {
    connections: HttpResponse[]; // array of raw NodeJS responses,
    // will contain more then one if we add few connections by the same clientId param
    meta?: Record<string, any>; // any meta you have added by meta param
    clientId: string; // client id you passed to or the one generated by lib
 };

getAllClientObjs([groupName])

Get connections and meta of all active clients

Params:

Param Type/Required Comment
groupName Type: string
Required: false
The group(namespace) where to get this clients from, if not provided it goes to default group

Method returns:

 Array<{
    connections: HttpResponse[]; // array of raw NodeJS responses,
    // will contain more then one if we add few connections by the same clientId param
    meta?: Record<string, any>; // any meta you have added by meta param
    clientId: string; // client id you passed to or the one generated by lib
 }>;

setClientMetadata(clientId [, groupName ])

Set client's meta

Params:

Param Type/Required Comment
clientId Type: string
Required: true
Id of client
meta Type: Record<string, any>
Required: true
Some meta you need to persist for this client
groupName Type: string
Required: false
The group(namespace) where to get this client by id from, if not provided it goes to default group

Method returns:

 {
    connections: HttpResponse[]; // array of raw NodeJS responses,
    // will contain more then one if we add few connections by the same clientId param
    meta?: Record<string, any>; // any meta you have added by meta param
    clientId: string; // client id you passed to or the one generated by lib
 };k

License

MIT

You might also like...

JavaScript framework for creating beautiful, fast and lightweight websites based on flutter way of coding ☜(゚ヮ゚☜)

Welcome to Flutjs project 😀 Flutjs is a javascript framework for creating beautiful, fast and lightweight websites. As the name suggests, Flutejs is

Nov 9, 2022

Blazing fast and lightweight state management framework 👓

Blazing fast and lightweight state management framework 👓

StateX is a blazing fast and lightweight framework for managing state in a Javascript app. Features 💨 Fast − Our APIs just run lightning fast, no mor

Oct 8, 2022

A Node.js framework for development of fast, simple, lightweight website.

MiuJS Web Framework A simple and minimal web framework using the JavaScript and Node.js. Featuring: builtin server multiple deploy target node vercel

Jun 19, 2022

A NodeJs service which allows you to create a movie based on it's title (additional movie details will be fetched) and fetch all created movies.

movies-api A NodeJs service which allows you to create a movie based on it's title (additional movie details will be fetched) and fetch all created mo

Mar 27, 2022

Lightweight library service that can dynamically make periodic updates to an Instagram profile.

instagram-dynamic-profile library This library uses the instagram-private-api to automate dynamic updates to an Instagram profile such as cycling thro

Sep 21, 2022

CLI Progress Bar implemented in NodeJS to track Time, ETA and Steps for any long running jobs in any loops in JS, NodeJS code

CLI Progress Bar implemented in NodeJS to track Time, ETA and Steps for any long running jobs in any loops in JS, NodeJS code

NodeJS-ProgressBar CLI Progress Bar for NodeJS and JavaScript to track Time, ETA and Steps for any long running jobs in any loops in JS, NodeJS code D

Nov 14, 2022

A CLI tool to create a NodeJS project with TypeScript CTSP is a CLI tool to make easier to start a new NodeJS project and configure Typescript on it.

A CLI tool to create a NodeJS project with TypeScript CTSP is a CLI tool to make easier to start a new NodeJS project and configure Typescript on it.

CTSP- Create TS Project A CLI tool to create a NodeJS project with TypeScript CTSP is a CLI tool to make easier to start a new NodeJS project and conf

Sep 13, 2022

A remote nodejs Cache Server, for you to have your perfect MAP Cache Saved and useable remotely. Easy Server and Client Creations, fast, stores the Cache before stopping and restores it again!

A remote nodejs Cache Server, for you to have your perfect MAP Cache Saved and useable remotely. Easy Server and Client Creations, fast, stores the Cache before stopping and restores it again!

remote-map-cache A remote nodejs Cache Server, for you to have your perfect MAP Cache Saved and useable remotely. Easy Server and Client Creations, fa

Oct 31, 2022

A lightweight Adobe Photoshop .psd/.psb file parser in typescript with zero-dependency for WebBrowser and NodeJS

@webtoon/psd A lightweight Adobe Photoshop .psd/.psb file parser in typescript with zero-dependency for WebBrowser and NodeJS Browser Support Chrome F

Jan 1, 2023
Owner
null
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A project for experimenting with Server Sent Events (SSE), a way of communication going from server to client.

A project for experimenting with Server Sent Events (SSE), a way of communication going from server to client.

Italo Menezes 4 May 16, 2022
Framework agnostic CLI tool for routes parsing and generation of a type-safe helper for safe route usage. 🗺️ Remix driver included. 🤟

About routes-gen is a framework agnostic CLI tool for routes parsing and generation of a type-safe helper for safe route usage. Think of it as Prisma,

Stratulat Alexandru 192 Jan 2, 2023
🏭 Framework-agnostic model factory system for clean testing

@julr/factorify Framework-agnostic model factory system for clean testing. Built-on top of Knex + Faker, and heavily inspired by Adonis.js and Laravel

Julien Ripouteau 14 Sep 29, 2022
Hadmean is an internal tool generator. It is language agnostic, schema driven, extremely customizable, featured packed, user-friendly and has just one installation step.

Hadmean Report a Bug · Request a Feature · Ask a Question Table of Contents About Quick Demo Motivation Why you should try Hadmean Getting Started Pre

Hadmean 344 Dec 29, 2022
Placebo, a beautiful new language agnostic diagnostics printer! It won't solve your problems, but you will feel better about them.

Placebo A beautiful new language agnostic diagnostics printer! ┌─[./README.md] │ > 1 │ What is Placebo? · ───┬──── ·

Robin Malfait 78 Dec 16, 2022
RESTful service to provide API linting as-a-service

API Linting Service Prerequisites / general idea General idea behind this API implementation is to provide an API as a service based on the awesome sp

Schwarz IT 6 Mar 14, 2022
TypeScript plugin for service-to-service (aka. "functionless") cloud integrations.

Functionless λ< Functionless is a TypeScript plugin that transforms TypeScript code into Service-to-Service (aka. "functionless") integrations, such a

sam 303 Jan 2, 2023