I am writing the server-side portion of an application in NodeJS with Express, which will use Server-Sent-Events (SSE). I have a solution that seems to work, but need to understand whether there is a better way of doing it in Node.
The relevant portion of code currently looks like this:
const headers = {
'Content-Type': 'text/event-stream',
'Connection': 'keep-alive',
'Cache-Control': 'no-cache',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true'
};
res.writeHead(200, headers);
// Do more stuff [...]
where res
is the response object.
Instead of calling res.writeHead()
, I have seen other examples use res.flushHeaders()
:
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Connection', 'keep-alive');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.flushHeaders();
Is there a difference between the two and is one preferable to the other, with respect to SSE and keeping a connection open to send messages?