Propuesta: Abstracción nativa/wrapper en Express para simplificar el manejo de respuestas SSE (Server-Sent Events)

Open
#7,334 5 comments 1 reaction 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
35/100
Issue type
Feature
Clarity
Needs clarification
Activity status
Quiet
Domain
api, backend

Research direction

The issue names no repository files or tests and provides only application-level setupSse, sendSse, and handlePreStreamError examples. Start by reviewing Express's existing response API and define the supported SSE abstraction, lifecycle, and error behavior; focused tests and an agreed API would mark the work complete.

Written by the indexing model from the issue text.

Description

discuss

actualmente estoy realizando un proyecto con express, no quiero usar websockets porque solo es un endpoint específico de mi app de express que necesita que se muestre la información en tiempo real, entonces una alternativa para ello es usar sse, que es también http pero da un funcionamiento parecido al de websocket, el problema es que implementarlo requiere un setup bastante riguroso en node, siento que se podría crear una abstracción en express para hacerlo mas facil asi como con las respuestas y esas cosas, porque actualmente para poder implementarlo tengo que configurar varios headers y el sistema de envió que siento que express puede simplificar mucho creando un wrapper para el envio de respuestas con sse, aqui adjunto un ejemplo del codigo que uso en mi app el cual es un wrapper para enviar respuestas por sse de manera facil

function handlePreStreamError(res, error) {
    if (res.headersSent) {
        sendSse(res, {
            type: "error",
            code: error.code || "SERVER_INTERNAL_ERROR",
            message: error.message || "Error interno del servidor",
        });
        return res.end();
    }

    return sendDomainError(res, error);
}

function sendSse(res, payload) {
    res.write(`data: ${JSON.stringify(payload)}\n\n`);
    res.flush?.();
}

function setupSse(res) {
    res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
    res.setHeader('Cache-Control', 'no-cache, no-transform');
    res.setHeader('Connection', 'keep-alive');
    res.setHeader('X-Accel-Buffering', 'no');
    res.flushHeaders?.();
}

ejemplo de uso relativo:

async function streamResponseController(req, res) {
    try {
        setupSse(res);

        sendSse(res, { type: "start", message: "Iniciando proceso..." });

        const data = await mockDataFunction(req.body);

        for await (const chunk of data) {
            if (res.writableEnded || req.aborted) {
                break;
            }

            sendSse(res, {
                type: "chunk",
                data: chunk,
            });
        }

        sendSse(res, { type: "done" });
        res.end();

    } catch (error) {
        handlePreStreamError(res, error);
    }
}
Dominant language
JavaScript
Stars
69.7k
Forks
25.6k
Avg merge
2d 9h
Merged PRs (30d)
4

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from expressjs/express

All issues in expressjs/express

Similar issues

More JavaScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.