Below is an example of a simple backend server using Node.js and Express that includes a Server-Sent Events (SSE) endpoint for a live feed. This example simulates a live feed by sending periodic updates to connected clients.
Prerequisites
Node.js installed on your machine
Basic understanding of JavaScript and Express
Steps
Initialize a Node.js project:
bash
mkdir sse-live-feed
cd sse-live-feed
npm init -y
npm install express
Create the backend server:
Create a file named server.js and add the following code:
javascript
const express = require('express');
const app = express();
const port = 3000;
// Middleware to set headers for SSE
const sseMiddleware = (req, res, next) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
next();
};
// Simulated live feed data
let feedCounter = 0;
const feedInterval = setInterval(() => {
feedCounter++;
}, 3000); // Update every 3 seconds
// SSE endpoint
app.get('/live-feed', sseMiddleware, (req, res) => {
const sendEvent = (data) => {
res.write(`data: ${JSON.stringify(data)}\n\n`);
};
// Send initial event
sendEvent({ id: feedCounter, message: 'Connected to live feed!' });
// Send periodic updates
const intervalId = setInterval(() => {
sendEvent({ id: feedCounter, message: `Update ${feedCounter}` });
}, 3000);
// Clean up on client disconnect
req.on('close', () => {
clearInterval(intervalId);
console.log('Client disconnected');
});
});
// Start the server
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
Run the server:
bash
node server.js
Test the SSE endpoint:
Open a browser or use a tool like curl to connect to the endpoint:
bash
curl -N http://localhost:3000/live-feed
Alternatively, you can create a simple HTML page to listen to the SSE feed: