Server Sent Event not working:: Error:: net::ERR_INCOMPLETE_CHUNKED_ENCODING 200

Viewed 1182

I have been trying to get basic server sent events up and running using following code(nodejs+express for backend and React on frontend), however the onmessage is not triggering when i try to update the count through terminal.

Here is the flow:

  1. Get the server up and running.
  2. Open browser and hit localhost:9000.
  3. In the UI, I can see Notification count is 0.
  4. Trying to update notification count using POST call in the terminal via cURL as below:

curl -X POST -H "Content-Type: application/json" -d '{"count": 10}' -s http://localhost:9000/notification

  1. In the terminal shell, where server is running, I can see that /events callback is triggered, however the count is still 0.

Here is the code i tried. Getting error as mentioned in the subject (seen in the browser's console) and UI does not update with updated notification count.Please let me know what am i doing wrong:

Server code(NodeJS+Express):

const sseHandler = (req: express.Request, res: express.Response) => {
console.log("server sent event handler triggered");
//Mandatory headers and http status to keep connection open
const headers = {
  'Content-Type': 'text/event-stream',
  'Connection': 'keep-alive',
  'Cache-Control': 'no-cache'
};

res.writeHead(200, headers);
//After client opens connection send all notifications as string
const data = `count:${notificationCount}\n\n`;
console.log(data);
res.write(data);
// Generate an id based on timestamp and save res
// object of client connection on clients list
// Later we'll iterate it and send updates to each client
// In Real world scenario, client list should be saved to the DB
const clientId = Date.now();
const newClient = {
  id: clientId,
  res,
};
clients.push(newClient);
// When client closes connection we update the clients list
// avoiding the disconnected one
req.on('close', () => {
  console.log(`${clientId} Connection closed`);
  clients = clients.filter(c => c.id !== clientId);
 });
};

// Iterate clients list and use write res object method to send latest notification count
const sendEventsToAll = (count:number) => {
  console.log("send event to all");
  clients.forEach(c => c.res.write(`count:${count}\n\n`));
};

// Middleware for POST /notification endpoint
const updateNotification = async (
  req: express.Request,
  res: express.Response,
) => {
  let currentCount= req.body.count;
  console.log("post count is: ", currentCount);
  // Send recently updated notification count as POST result
  res.json({count: currentCount});
  // Invoke iterate and send function
  return sendEventsToAll(currentCount);
}

React Code

const Nav = () => {
const router = useRouter();
const [ notificationCount, setNotificationCount ] = useState(0);

useEffect(() => {
  console.log("rendered on client");
  const events = new EventSource('http://localhost:9000/events');
  events.onmessage = (event) => {
    console.log("Entering on message callback");
    console.log(event);
    // console.log(event.data);
    // const parsedData = JSON.parse(event.data);
    // setNotificationCount(() => parsedData.count);
  };
}, [notificationCount]);

// record rendering counter
metrics.recordCounter({
  name: "NavBar",
  eventName: "render",
  value: 1,
});

return (
  <nav>
    <ul>
      <li className={router.pathname === "/" ? "active" : ""}>
        <Link href="/">
          <a>Home</a>
        </Link>
      </li>
      <li className={router.pathname === "/dangerously_set" ? "active" : ""}>
        <Link href="/xss-testing">
          <a>XSS Testing</a>
        </Link>
      </li>
      {links.map(({ key, href, label }) => (
        <li key={key}>
          <a href={href}>{label}</a>
        </li>
      ))}
      <a href="#" className="notification">
        <span>Notification</span>
        <span className="badge">{notificationCount}</span>
      </a>
    </ul>
  );
 }
1 Answers

I had to stop default compression of response body which did the trick. Here is the check i placed (response header check on Content-Type):

const shouldCompress = (
  req: express.Request,
  res: express.Response
): boolean => {
// don't compress responses explicitly asking not
if (req.headers["x-no-compression"] || res.getHeader('Content-Type') === 'text/event-stream') {
  return false;
}

// use compression filter function
  return compression.filter(req, res);
};

My nodejs+express code uses compression middleware as below:

import compression from "compression";
...
..
.
.
.
/**
 * Express application setup
*/
const expressApp = express();

// setup compression in express
expressApp.use(compression({ filter: shouldCompress }));

Also, response from server should have following fields: https://javascript.info/server-sent-events#server-response-format

Related