typescriptintermediate

Server-Sent Events Handler

Express route that implements SSE for real-time server-to-client push notifications.

typescript
import { Request, Response } from 'express';

const clients = new Set<Response>();

export function sseHandler(req: Request, res: Response) {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    Connection: 'keep-alive',
  });

  res.write('data: connected\n\n');
  clients.add(res);

  req.on('close', () => {
    clients.delete(res);
  });
}

export function broadcast(event: string, data: unknown) {
  const message = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
  for (const client of clients) {
    client.write(message);
  }
}

Use Cases

  • Live notifications
  • Real-time dashboards

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.