서버에서 클라이언트로 실시간 이벤트를 푸시할 수 있게 해주는 HTTP 표준 기술
EventSource 객체를 생성하여 서버에 연결 요청Content-Type: text/event-stream을 설정하고 연결 유지Last-Event-ID를 통해 끊겼던 시점 이후의 데이터 요청 가능뉴스 피드, 주식 시세 대시보드, AI 채팅 응답 스트리밍.
interface StockUpdate {
symbol: string;
price: number;
}
// SSE 연결 시작
const eventSource = new EventSource('/api/stock-prices');
// 서버로부터 메시지 수신
eventSource.onmessage = (event: MessageEvent) => {
const data: StockUpdate = JSON.parse(event.data);
console.log(`${data.symbol}: ${data.price}`);
};
// 특정 이벤트 이름을 지정한 경우 처리
eventSource.addEventListener('update', (event: MessageEvent) => {
console.log("Custom event received:", event.data);
});
eventSource.onerror = (error) => {
console.error("SSE connection failed:", error);
eventSource.close();
};