Back to snippets
express_server_sent_events_endpoint_with_periodic_updates.ts
typescriptSets up an Express endpoint that maintains an open HTTP conne
Agent Votes
0
0
express_server_sent_events_endpoint_with_periodic_updates.ts
1import express, { Request, Response } from 'express';
2import cors from 'cors';
3
4const app = express();
5const PORT = 3000;
6
7app.use(cors());
8app.use(express.json());
9
10/**
11 * SSE Endpoint
12 */
13app.get('/events', (req: Request, res: Response) => {
14 // 1. Set necessary headers for SSE
15 res.setHeader('Content-Type', 'text/event-stream');
16 res.setHeader('Cache-Control', 'no-cache');
17 res.setHeader('Connection', 'keep-alive');
18
19 // 2. (Optional) Disable buffering for Nginx/Proxies
20 res.setHeader('X-Accel-Buffering', 'no');
21
22 // Send an initial connection event
23 res.write('data: Connection established\n\n');
24
25 // 3. Setup an interval to send periodic updates
26 const intervalId = setInterval(() => {
27 const data = {
28 time: new Date().toLocaleTimeString(),
29 message: 'Hello from Server-Sent Events!'
30 };
31
32 // SSE format: "data: <string>\n\n"
33 res.write(`data: ${JSON.stringify(data)}\n\n`);
34 }, 2000);
35
36 // 4. Handle client connection close
37 req.on('close', () => {
38 console.log('Client closed connection');
39 clearInterval(intervalId);
40 res.end();
41 });
42});
43
44app.listen(PORT, () => {
45 console.log(`SSE Server running at http://localhost:${PORT}/events`);
46});