typescriptintermediate
Server-Sent Events Handler
Express route that implements SSE for real-time server-to-client push notifications.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
typescriptadvanced
Streaming API Response
Stream long-running API responses using ReadableStream and TransformStream for real-time data delivery.
Best for: AI response streaming
#streaming#api
typescriptadvanced
Streaming Response from Route Handler
Stream large responses from Next.js route handlers using ReadableStream for real-time data.
Best for: real-time updates
#nextjs#streaming
pythonbeginner
Stream LLM Chat Responses
Stream OpenAI chat completions token-by-token for real-time UI updates.
Best for: Chat UIs
#ai#streaming
pythonintermediate
OpenAI Streaming with SSE in FastAPI
Stream OpenAI responses as Server-Sent Events from a FastAPI endpoint.
Best for: streaming AI APIs
#openai#fastapi