Server-Sent Events
One-way event streaming from server to client
One-way event streaming from server to client
Server-Sent Events (SSE) is a web standard technology for streaming real-time data in one direction, from the server to the client. Because the server can push events while keeping an HTTP connection open, real-time features can be implemented more simply than with WebSocket.
SSE uses the text/event-stream MIME type and is a text protocol composed of the 'data:', 'event:', 'id:', and 'retry:' fields. It connects easily through the browser's EventSource API, and automatic reconnection is built in.
Typical use cases for SSE include real-time notifications, stock quotes, social media feeds, and streaming AI chatbot responses. LLM services such as ChatGPT use SSE when streaming responses token by token.
Compared with WebSocket, SSE supports only one-way communication, but it allows multiplexing over HTTP/2 and is compatible with existing HTTP infrastructure (proxies, load balancers). If two-way communication is not needed, SSE is more efficient.
// Node.js/Express SSE ์๋ฒ
import express from 'express';
const app = express();
app.get('/api/events', (req, res) => {
// SSE ํค๋ ์ค์
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders();
// ์ฐ๊ฒฐ ID ์ ์ก
const clientId = Date.now();
res.write(`id: ${clientId}\n`);
res.write(`event: connected\n`);
res.write(`data: {"clientId": "${clientId}"}\n\n`);
// ์ฃผ๊ธฐ์ ์ผ๋ก ๋ฐ์ดํฐ ์ ์ก
const interval = setInterval(() => {
const data = JSON.stringify({
time: new Date().toISOString(),
price: Math.random() * 100
});
res.write(`data: ${data}\n\n`);
}, 1000);
// ์ฐ๊ฒฐ ์ข
๋ฃ ์ฒ๋ฆฌ
req.on('close', () => {
clearInterval(interval);
res.end();
});
});
// Next.js App Router SSE
// app/api/chat/route.ts
export async function GET(request: Request) {
const encoder = new TextEncoder();
const stream = new ReadableStream({
async start(controller) {
// AI ์๋ต ์๋ฎฌ๋ ์ด์
const tokens = ['์๋
', 'ํ์ธ์', '!', ' ', '๋ฌด์์', ' ', '๋์', '๋๋ฆด๊น์', '?'];
for (const token of tokens) {
const data = `data: ${JSON.stringify({ token })}\n\n`;
controller.enqueue(encoder.encode(data));
await new Promise(r => setTimeout(r, 100));
}
controller.enqueue(encoder.encode('data: [DONE]\n\n'));
controller.close();
}
});
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
},
});
}
// ํด๋ผ์ด์ธํธ EventSource ์ฌ์ฉ
function ChatStream() {
const [messages, setMessages] = useState('');
useEffect(() => {
const eventSource = new EventSource('/api/chat');
eventSource.onmessage = (event) => {
if (event.data === '[DONE]') {
eventSource.close();
return;
}
const { token } = JSON.parse(event.data);
setMessages(prev => prev + token);
};
eventSource.onerror = () => eventSource.close();
return () => eventSource.close();
}, []);
return <div>{messages}</div>;
}
In a technical meeting:
"The AI response typing effect can be implemented with SSE. If you stream token by token, the text appears in real time just like ChatGPT. It's also easier to implement than WebSocket."
In a technical interview:
"What's the difference between SSE and WebSocket?" - "SSE is one-way from server to client, while WebSocket is two-way. SSE uses the HTTP protocol, so it is highly compatible with existing infrastructure, and it also supports automatic reconnection."
In a code review:
"Add reconnection logic for when the SSE connection drops. EventSource reconnects automatically, but if you don't call close() when the component unmounts, you'll get a memory leak."
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free