Server Side Events / Chrome Errors

839 views Asked by At

I'm experiencing a console error on Chrome & Firefox after every few minutes but events are still coming through - this continues on for a while until eventually Chrome logs a 520 error & Firefox 'can't establish a connection to the server' resulting in the eventsource breaking completely.

I tested this locally and no issues at all in either browser. The difference in our production environment is that we are behind an nginx proxy and CloudFlare security.

These are the headers I'm using in the backend:

  'Connection': 'keep-alive',
  'Content-Type': 'text/event-stream',
  'Cache-Control': 'no-cache',
  'X-Accel-Buffering': 'no'

This is the code in the backend (node JS)

res.writeHead(200, headers);
res.setTimeout(1000 * 60 * 120)
res.flushHeaders()
req.on('close', () => {      
  res.end()
})
res.on('timeout', () => res.end())

And these are the nginx configurations I have tried:

proxy_set_header Connection '';
proxy_http_version 1.1;
chunked_transfer_encoding off;
proxy_buffering off;
proxy_cache off;
http2_max_field_size 64k;
http2_max_header_size 512k;
proxy_read_timeout 12h;

Front-end code

 let source = new EventSource('/events')
 source.onerror = (e) => console.log(e)
 source.onmessage = (msg) => console.log(msg)

Chrome Console: enter image description here

Appreciate any advice. Thanks

Firefox console: enter image description here

1

There are 1 answers

0
Grapes On

I've went through this myself and it turned out to be caused by CloudFlare proxy. Seems CloudFlare will terminate the connection after some time.

To solve this simply turn off the CloudFlare proxy as described here: https://docs.readme.com/docs/turn-off-cloudflare-proxy

Make sure to create a subdomain so you don't disable proxying for your entire website.