Skip to content

Instantly share code, notes, and snippets.

@maanimis
Last active February 15, 2025 18:35
Show Gist options
  • Save maanimis/5deb464a41df9821fb36a7f6a733fe73 to your computer and use it in GitHub Desktop.
Save maanimis/5deb464a41df9821fb36a7f6a733fe73 to your computer and use it in GitHub Desktop.
Server-Sent Events (SSE) in Node.js using Express

From chatgpt

Handling Load Balancers

  • SSE requires sticky sessions if behind a load balancer, like Nginx.
  • Example Nginx config for SSE:
location /events {
    proxy_pass http://your-node-server;
    proxy_set_header Connection '';
    proxy_buffering off;
}

Running the Server in Production

NODE_ENV=production node server.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Production SSE</title>
</head>
<body>
<h1>Production-Grade SSE</h1>
<div id="events"></div>
<script>
const eventSource = new EventSource("http://localhost:3000/events");
eventSource.onmessage = function (event) {
const data = JSON.parse(event.data);
const eventsDiv = document.getElementById("events");
eventsDiv.innerHTML += `<p>${data.message} (Time: ${new Date(data.timestamp).toLocaleTimeString()})</p>`;
};
eventSource.onerror = function () {
console.error("EventSource error, attempting to reconnect...");
eventSource.close();
};
</script>
</body>
</html>
const express = require("express");
const compression = require("compression");
const cors = require("cors");
const app = express();
const PORT = process.env.PORT || 3000;
// Enable compression for SSE efficiency
app.use(compression());
// Enable CORS (only allow specific origins in production)
app.use(cors({ origin: "http://yourfrontend.com" }));
// Store active connections
const clients = new Set();
// SSE Route
app.get("/events", (req, res) => {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
// Add client to the set
clients.add(res);
// Send initial message
res.write(`data: ${JSON.stringify({ message: "Connected to SSE" })}\n\n`);
// Cleanup when client disconnects
req.on("close", () => {
clients.delete(res);
res.end();
});
});
// Function to broadcast messages to all clients
function broadcast(data) {
for (const client of clients) {
client.write(`data: ${JSON.stringify(data)}\n\n`);
}
}
// Simulate data every 2 seconds
setInterval(() => {
broadcast({ message: "Real-time update", timestamp: Date.now() });
}, 2000);
app.listen(PORT, () => {
console.log(`🚀 SSE Server running on http://localhost:${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment