SSE connection not established

Viewed 138

I have implemented Server-Sent events with fastify.

The client code:

      const url = `${server}/sse/events`;

      const connection = new EventSource(url);
      connection.onopen = () => {
        console.log('The connection has been established.');
      };

      connection.onerror = (error: any) => {
        console.log('Connection error', error);
        connection.close();
      };

The server code(controller of route /sse/events):

const establishSSEConnection = async function (request, reply) {

    // some application logic

    let headers = {
        'Content-Type': 'text/event-stream',
        Connection: 'keep-alive',
        'Cache-Control': 'no-cache',
        'Access-Control-Allow-Origin': '*',
    };
    reply.raw.writeHead(200, headers);
    reply.raw.flushHeaders();
    headers = null;

    reply.sent = true;
    request.socket.on('close', () => {
        console.log('SSE connection closed');
    });
};

So, when I test this locally with docker everything seems fine and The connection has been established. is printed out. When I deploy it to kubernetes though, the log is never printed and after a while the SSEconnection closed is logged.

So the question is why does this work in docker and not in kubernetes? Has anyone encountered this problem before? Any help would be highly appreciated.

Thank you!

1 Answers

The GET request for the connection seemed as pending in the browser. I added reply.raw.write('OK\n\n'); in the establishSSEConnection handler and it worked!

Related