### Install ExpreSSE using Yarn Source: https://github.com/toverux/expresse/blob/master/README.md This command demonstrates how to install the ExpreSSE package as a project dependency using the Yarn package manager. It fetches the latest version from the npm registry. ```Shell yarn add @toverux/expresse ``` -------------------------------- ### Basic sse() Middleware Usage Example Source: https://github.com/toverux/expresse/blob/master/README.md Provides a TypeScript example demonstrating how to use the sse() middleware in an Express route. It shows how to send different types of SSE messages (data, named events, comments) and handle the Last-Event-ID header for message replay. ```typescript // somewhere in your module router.get('/events', sse(/* options */), (req, res: ISseResponse) => { let messageId = parseInt(req.header('Last-Event-ID'), 10) || 0; someModule.on('someEvent', (event) => { //=> Data messages (no event name, but defaults to 'message' in the browser). res.sse.data(event); //=> Named event + data (data is mandatory) res.sse.event('someEvent', event); //=> Comment, not interpreted by EventSource on the browser - useful for debugging/self-documenting purposes. res.sse.comment('debug: someModule emitted someEvent!'); //=> In data() and event() you can also pass an ID - useful for replay with Last-Event-ID header. res.sse.data(event, (messageId++).toString()); }); // (not recommended) to force the end of the connection, you can still use res.end() // beware that the specification does not support server-side close, so this will result in an error in EventSource. // prefer sending a normal event that asks the client to call EventSource#close() itself to gracefully terminate. someModule.on('someFinishEvent', () => res.end()); }); ``` -------------------------------- ### Using RedisHub with sseHub Middleware Source: https://github.com/toverux/expresse/blob/master/README.md Shows how to use `RedisHub`, a subclass of `Hub` that leverages Redis pub/sub for broadcasting messages across multiple server instances. It provides examples for connecting to the default Redis port or specifying custom Redis client instances. ```TypeScript // connects to localhost:6379 (default Redis port) const hub = new RedisHub('channel-name'); // ...or you can pass you own two ioredis clients to bind on a custom network address const hub = new RedisHub('channel-name', new Redis(myRedisNodeUrl), new Redis(myRedisNodeUrl)); router.get('/channel', sseHub({ hub }), (req, res: ISseHubResponse) => { res.sse.event('welcome', 'Welcome!'); // 1-to-1 res.sse.broadcast.event('new-user', `User ${req.query.name} just hit the /channel endpoint`); }); ``` -------------------------------- ### Using sseHub Middleware (Client Controls Hub) Source: https://github.com/toverux/expresse/blob/master/README.md Illustrates a basic usage scenario where the `sseHub` middleware automatically creates and manages the `Hub` instance. It shows how to use both the 1-to-1 `res.sse` functions and the broadcasting `res.sse.broadcast` functions within a route handler. ```TypeScript // somewhere in your module router.get('/events', sseHub(/* options */), (req, res: ISseHubResponse) => { //=> The 1-to-1 functions are still there res.sse.event('welcome', 'Welcome!'); //=> But we also get a `broadcast` property with the same functions inside. // Everyone that have hit /events will get this message - including the sender! res.sse.broadcast.event('new-user', `User ${req.query.name} just hit the /channel endpoint`); }); ``` -------------------------------- ### Importing sseHub Middleware (CommonJS) Source: https://github.com/toverux/expresse/blob/master/README.md Demonstrates how to import the `Hub` and `sseHub` components using CommonJS syntax, suitable for Node.js environments without ES modules. ```JavaScript const { Hub, sseHub } = require('@toverux/expresse'); ``` -------------------------------- ### Using sseHub Middleware (External Hub) Source: https://github.com/toverux/expresse/blob/master/README.md Demonstrates a more common pattern where a `Hub` instance is created outside the middleware and passed as an option. This allows external modules or event handlers to broadcast messages through the same hub instance. ```TypeScript const hub = new Hub(); someModule.on('someEvent', (event) => { //=> All the functions you're now used to are still there, data(), event() and comment(). hub.event('someEvent', event); }); router.get('/events', sseHub({ hub }), (req, res: ISseHubResponse) => { //=> The 1-to-1 functions are still there res.sse.event('welcome', 'Welcome! You'll now receive realtime events from someModule like everyone else'); }); ``` -------------------------------- ### Importing sse() middleware (CommonJS) Source: https://github.com/toverux/expresse/blob/master/README.md Shows how to import the sse() middleware using the CommonJS require() syntax, typically used in Node.js environments without ES modules. ```javascript const { sse } = require('@toverux/expresse'); ``` -------------------------------- ### sseHub Middleware Configuration Options Interface Source: https://github.com/toverux/expresse/blob/master/README.md Defines the TypeScript interface for the configuration options accepted by the `sseHub()` middleware. It extends `ISseMiddlewareOptions` and adds a `hub` property to allow providing a custom `Hub` instance. ```TypeScript interface ISseHubMiddlewareOptions extends ISseMiddlewareOptions { /** * You can pass a Hub instance for controlling the stream outside of the middleware. * Otherwise, a Hub is automatically created. * * @default Hub */ hub: Hub; } ``` -------------------------------- ### Importing sse() middleware (ES 2015) Source: https://github.com/toverux/expresse/blob/master/README.md Demonstrates how to import the sse() middleware and the ISseResponse interface using ES 2015 import syntax in TypeScript and JavaScript. Note that ISseResponse is a TypeScript-only interface. ```typescript import { ISseResponse, sse } from '@toverux/expresse'; // named export { sse } is also exported as { default }: import sse from '@toverux/expresse'; ``` -------------------------------- ### Configuring expresse with compression middleware in Express (TypeScript) Source: https://github.com/toverux/expresse/blob/master/README.md This snippet demonstrates how to configure an Express application to use both compression middleware (like expressjs/compression) and expresse for Server-Sent Events (SSE). It shows the essential `flushAfterWrite: true` option required for expresse to work correctly when compression is enabled, preventing response buffering that interferes with SSE streaming. ```TypeScript app.use(compression()); app.get('/events', sse({ flushAfterWrite: true }), (req, res: ISseResponse) => { res.sse.comment('Welcome! This is a compressed SSE stream.'); }); ``` -------------------------------- ### Importing sseHub Middleware (ES 2015) Source: https://github.com/toverux/expresse/blob/master/README.md Demonstrates how to import the `Hub`, `ISseHubResponse`, and `sseHub` components using ES 2015 syntax. `ISseHubResponse` is a TypeScript interface and should not be imported in JavaScript projects. ```TypeScript import { Hub, ISseHubResponse, sseHub } from '@toverux/expresse'; ``` -------------------------------- ### ISseMiddlewareOptions Interface Source: https://github.com/toverux/expresse/blob/master/README.md Defines the TypeScript interface for the configuration options available for the sse() middleware. It includes options for message serialization, header flushing, keep-alive intervals, and compatibility with expressjs/compression. ```typescript interface ISseMiddlewareOptions { /** * Serializer function applied on all messages' data field (except when you direclty pass a Buffer). * SSE comments are not serialized using this function. * * @default JSON.stringify */ serializer?: (value: any) => string | Buffer; /** * Whether to flush headers immediately or wait for the first res.write(). * - Setting it to false can allow you or 3rd-party middlewares to set more headers on the response. * - Setting it to true is useful for debug and tesing the connection, ie. CORS restrictions fail only when headers * are flushed, which may not happen immediately when using SSE (it happens after the first res.write call). * * @default true */ flushHeaders?: boolean; /** * Determines the interval, in milliseconds, between keep-alive packets (neutral SSE comments). * Pass false to disable heartbeats (ie. you only support modern browsers/native EventSource implementation and * therefore don't need heartbeats to avoid the browser closing an inactive socket). * * @default 5000 */ keepAliveInterval?: false | number; /** * If you are using expressjs/compression, you MUST set this option to true. * It will call res.flush() after each SSE messages so the partial content is compressed and reaches the client. * Read {@link https://github.com/expressjs/compression#server-sent-events} for more. * * @default false */ flushAfterWrite?: boolean; } ``` -------------------------------- ### Configuring Custom Serializer for SSE Data Source: https://github.com/toverux/expresse/blob/master/README.md Explains how to override the default JSON serialization for the `data` field of SSE messages by providing a custom `serializer` function in the `sse()` middleware options. The serializer must accept a value and return a string or Buffer. ```TypeScript app.get('/events', sse({ serializer: String }), yourMiddleware); // or, less optimized: app.get('/events', sse({ serializer: data => data.toString() }), yourMiddleware); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.