0.2.0 • Published 5 years ago

http-event-stream v0.2.0

Weekly downloads
77
License
MIT
Repository
github
Last release
5 years ago

http-event-stream Build Status NPM Version

Create plain HTTP event streams using Server Sent Events (SSE) in node.js. Stream push notifications to the client without WebSockets.

Framework-agnostic: Works with Express, Koa and probably many more. Check out Differences to WebSockets below.

📡  Realtime events over plain HTTP 💡  Serve as a REST endpoint route ☁️  Stateless by design 👌  Simple unopinionated API

Installation

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

Usage

Using Express.js

const express = require("express")
const { streamEvents } = require("http-event-stream")

const app = express()

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

app.listen(3000)

Using Koa.js

const Koa = require("koa")
const Router = require("koa-router")
const { createEventStream } = require("http-event-stream")

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

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

  // 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

function streamSampleEvents (req, res) {
  const fetchEventsSince = async (lastEventId) => {
    return [ /* all events since event with ID `lastEventId` woud 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 (streamContext) {
      // Sample events: Send an event every second
      const interval = setInterval(() => {
        streamContext.sendEvent({
          event: "time",
          data: {
            now: new Date().toISOString()
          }
        })
      }, 1000)

      // Return stream-closing function
      const unsubscribe = () => clearInterval(interval)
      return unsubscribe
    }
  })
}

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

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

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

0.2.0

5 years ago

0.1.2

6 years ago

0.1.1

6 years ago

0.1.0

6 years ago