Server-sent events

Stric provides the SSE class for sending events to client.

import { Router } from '@stricjs/router';
import { SSE } from '@stricjs/utils';

const sse = new SSE('/events')
    .use(req => {
        req.controller // Use this to send events while signal not aborted
    })
    .abort(req => {
        // Handle abort (remember to close the readable stream)
    });
    
export default new Router().plug(sse);

For lower-level control, consider using the writer method.

import { Router } from '@stricjs/router';
import { writer } from '@stricjs/utils';

export default new Router()
    .get('/events', writer(
        req => {
            req.controller
            // Write something to the controller
            // Remember to manually close the readable stream
        }
    ));

This method wraps the request handler inside a direct ReadableStream.

Last updated