title: How to turn off buffering on Nginx Server for Server sent event
body: <p>Problem : Nginx Server is buffring the Server sent events(SSE). </p>
  
  <p>Setup : Node v12.13.1, Nginx 1.16.1, Chrome v80</p>
  
  <p>Scenario:
  I tried to turn off buffering with <code>proxy_buffering off;</code> and even added <code>"X-Accel-Buffering": "no"</code> in server resonse header however nginx is still buffering all SSE. if I close node server or restart nginx server then all the SSE message are delivered to client in bulk. I tried alot but dont know that I'm missing.</p>
  
  <p>Nginx Config file :</p>
  
  <pre><code>
  events {
      worker_connections  1024;
  }
  
  http {
      include       mime.types;
      sendfile        on;   
      keepalive_timeout  65;
  
      server {
          listen       4200;
          server_name  localhost;
  
          location / {    
              proxy_set_header Connection '';
              proxy_http_version 1.1;
              chunked_transfer_encoding off;
              proxy_buffering off;
              proxy_cache off;
              proxy_pass http://localhost:8700;
          }
      }
  }
  </code></pre>
  
  <p>Node Server :</p>
  
  <pre><code>var express = require('express');
  var app = express();
  
  var template = 
  `&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt;
      &lt;script type="text/javascript"&gt;
          var source = new EventSource("/events/");
          source.onmessage = function(e) {
              document.body.innerHTML += e.data + "&lt;br&gt;";
          };
      &lt;/script&gt;
  &lt;/body&gt; &lt;/html&gt;`;
  
  app.get('/', function (req, res) {
      res.send(template); // &lt;- Return the static template above
  });
  
  var clientId = 0;
  var clients = {}; // &lt;- Keep a map of attached clients
  
  // Called once for each new client. Note, this response is left open!
  app.get('/events/', function (req, res) {
      req.socket.setTimeout(Number.MAX_VALUE);
      res.writeHead(200, {
          'Content-Type': 'text/event-stream', // &lt;- Important headers
          'Cache-Control': 'no-cache',
          'Connection': 'keep-alive',
          'X-Accel-Buffering': 'no'
      });
      res.write('\n');
      (function (clientId) {
          clients[clientId] = res; // &lt;- Add this client to those we consider "attached"
          req.on("close", function () {
              delete clients[clientId]
          }); // &lt;- Remove this client when he disconnects
      })(++clientId)
  });
  
  setInterval(function () {
      var msg = Math.random();
      console.log("Clients: " + Object.keys(clients) + " &lt;- " + msg);
      for (clientId in clients) {
          clients[clientId].write("data: " + msg + "\n\n"); // &lt;- Push a message to a single attached client
      };
  }, 2000);
  
  app.listen(process.env.PORT || 8700);
  </code></pre>