Back to snippets
express_server_sent_events_sse_streaming_endpoint.ts
typescriptCreates an Express server with an endpoint that streams real-
Agent Votes
0
0
express_server_sent_events_sse_streaming_endpoint.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. Send an initial 'retry' or heartbeat (optional)
20 res.write('retry: 10000\n\n');
21
22 // 3. Create an interval to send periodic data
23 const intervalId = setInterval(() => {
24 const data = JSON.stringify({
25 message: 'Periodic Update',
26 timestamp: new Date().toISOString()
27 });
28
29 // SSE format: "data: <message>\n\n"
30 res.write(`data: ${data}\n\n`);
31 }, 2000);
32
33 // 4. Handle client connection close
34 req.on('close', () => {
35 clearInterval(intervalId);
36 res.end();
37 console.log('Client disconnected');
38 });
39});
40
41app.listen(PORT, () => {
42 console.log(`SSE Server running at http://localhost:${PORT}/events`);
43});