All Projects β†’ andywer β†’ http-event-stream

andywer / http-event-stream

Licence: MIT License
πŸ“‘ Modern spec-compliant Server Sent Events stream implementation.

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to http-event-stream

Php Sse
A simple and efficient library implemented HTML5's server-sent events by PHP, is used to real-time push events from server to client, and easier than Websocket, instead of AJAX request.
Stars: ✭ 237 (+1381.25%)
Mutual labels:  events, sse, server-sent-events
sse
HTML5 Server-Sent-Events for Go
Stars: ✭ 84 (+425%)
Mutual labels:  events, sse, server-sent-events
Reddit sse stream
A Server Side Event stream to deliver Reddit comments and submissions in near real-time to a client.
Stars: ✭ 39 (+143.75%)
Mutual labels:  stream, sse
SSE-Github
This repository contains the demo app for the blog
Stars: ✭ 17 (+6.25%)
Mutual labels:  expressjs, sse
mindjs
Minimalistic, pure Node.js framework superpowered with Dependency Injection πŸ’‘ πŸ’» πŸš€
Stars: ✭ 17 (+6.25%)
Mutual labels:  expressjs, koajs
Server Push Hooks
πŸ”₯ React hooks for Socket.io, SEE, WebSockets and more to come
Stars: ✭ 176 (+1000%)
Mutual labels:  sse, server-sent-events
Httperrorpages
⏩ Simple HTTP Error Page Generator
Stars: ✭ 772 (+4725%)
Mutual labels:  expressjs, koajs
go-sse
Fully featured, spec-compliant HTML5 server-sent events library
Stars: ✭ 165 (+931.25%)
Mutual labels:  sse, server-sent-events
Demo.AspNetCore.ServerSentEvents
Demo project for demonstrating functionality of Lib.AspNetCore.ServerSentEvents
Stars: ✭ 52 (+225%)
Mutual labels:  sse, server-sent-events
geo-smart-system
Open Source Realtime Tracking System
Stars: ✭ 36 (+125%)
Mutual labels:  sse, server-sent-events
go-gin-web-server
Deploy Go Gin on Render
Stars: ✭ 23 (+43.75%)
Mutual labels:  sse, server-sent-events
Lib.aspnetcore.serversentevents
Lib.AspNetCore.ServerSentEvents is a library which provides Server-Sent Events (SSE) support for ASP.NET Core
Stars: ✭ 138 (+762.5%)
Mutual labels:  sse, server-sent-events
Demo Spring Sse
'Server-Sent Events (SSE) in Spring 5 with Web MVC and Web Flux' article and source code.
Stars: ✭ 102 (+537.5%)
Mutual labels:  sse, server-sent-events
Routing Controllers Openapi
Runtime OpenAPI v3 schema generation for routing-controllers.
Stars: ✭ 170 (+962.5%)
Mutual labels:  expressjs, koajs
Axway Amplify Streams Js
AMPLIFY Streams Javascript package containing SDK, documentation and sample applications
Stars: ✭ 79 (+393.75%)
Mutual labels:  sse, server-sent-events
Golang Sse Todo
golang server sent events (sse) example
Stars: ✭ 23 (+43.75%)
Mutual labels:  sse, server-sent-events
Swell
Swell: API development tool that enables developers to test endpoints served over streaming technologies including Server-Sent Events (SSE), WebSockets, HTTP2, GraphQL, and gRPC.
Stars: ✭ 517 (+3131.25%)
Mutual labels:  sse, server-sent-events
Eventsource
EventSource client for Node.js and Browser (polyfill)
Stars: ✭ 541 (+3281.25%)
Mutual labels:  sse, server-sent-events
go-sse
Server-Sent Events for Go
Stars: ✭ 106 (+562.5%)
Mutual labels:  sse, server-sent-events
psql-streamer
Stream database events from PostgreSQL to Kafka
Stars: ✭ 37 (+131.25%)
Mutual labels:  events, stream

http-event-stream Build Status NPM Version

Stream real-time events over plain HTTP using Server Sent Events (SSE) in node.js.

Focusing on spec-compliant Server Sent Event streams, we not only stream events, but also replay past events on demand. Event replaying allows clients to disconnect and reconnect to a stream without missing any data.

πŸ“‘  Server-sent events via plain HTTP
πŸ’‘  Stream as a REST endpoint route
☁️  Immutable state allows cleaner code
πŸ—ΊοΈ  Framework-agnostic - works with Express, Koa & others
πŸ›‘οΈ  No more "Failed to upgrade websocket connection"


Installation

npm install http-event-stream
# or
yarn add http-event-stream

Usage

Using Express.js

const express = require("express")

const app = express()

// Example event stream: Stream the current time
app.get("/time-stream", (req, res) => {
  // Find the implementation below
  streamSampleEvents(req, res)
})

app.listen(3000)

Using Koa.js

const Koa = require("koa")
const Router = require("koa-router")

const app = new Koa()
const router = new Router()

// Example event stream: Stream the current time
router.get("/time-stream", (context) => {
  // Find the implementation below
  streamSampleEvents(context.req, context.res)

  // Koa quirk: Don't close the request/stream after handling the route!
  context.respond = false
})

app
  .use(router.routes())
  .use(router.allowedMethods())
  .listen(3000)

Sample stream implementation

const { streamEvents } = require("http-event-stream")
const events = require("./some-event-emitter")

function streamSampleEvents (req, res) {
  const fetchEventsSince = async (lastEventId) => {
    return [ /* all events since event with ID `lastEventId` would go here */ ]
  }
  return streamEvents(req, res, {
    async fetch (lastEventId) {
      // This method is mandatory to replay missed events after a re-connect
      return fetchEventsSince(lastEventId)
    },
    stream (stream) {
      const listener = () => {
        stream.sendEvent({
          event: "time",
          data: JSON.stringify({
            now: new Date().toISOString()
          })
        })
      }

      // Subscribe to some sample event emitter
      events.addEventListener("data", listener)

      // Return an unsubscribe function, so the stream can be terminated properly
      const unsubscribe = () => events.removeEventListener("data", listener)
      return unsubscribe
    }
  })
}

A server-sent event sent via stream.sendEvent() or returned from fetch() has to have the following shape:

interface ServerSentEvent {
  data: string | string[]
  event?: string,
  id?: string
  retry?: number
}

Besides stream.sendEvent(event: ServerSentEvent) there is also stream.sendComment(comment: string) and stream.close().

See Using server-sent events - Fields.

API

See dist/index.d.ts.

Differences to WebSockets

Brief summary:

  • Automatic reconnecting out of the box
  • Unidirectional data flow
  • HTTP/2 multiplexing out of the box
  • No Connection: Upgrade - no special reverse proxy config

What do we use websockets for? Usually for streaming events from the server to client in realtime.

Server Sent Events (SSE) only do this one job, but do it really well. It's a simple protocol, using a normal HTTP connection, only streaming data from the server to the client.

You can pass parameters and headers from the client to the server when opening the stream, but the actual stream is read-only for the client.

It might sound like a strong limitation first, but actually it's a pretty clean approach: It makes the stream stateless and allows cool things like combining multiple streams into one which you could not easily do with a duplex stream.

Authentication

Since it's all just plain HTTP, we can use headers like we always do. Go ahead and use your favorite auth middleware that you use for the other REST endpoints.

Client

Make sure to include a polyfill in your web page code, since not all major browsers provide native support for SSE.

Try event-source-polyfill.

To connect to SSE streams from node.js, use the eventsource package.

Further reading

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].