๐ŸŒ Web Development

Server-Sent Events

One-way event streaming from server to client

๐Ÿ“– Detailed Explanation

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.

๐Ÿ’ป Code Example

// 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>;
}

๐Ÿ—ฃ๏ธ Examples of Practical Conversations

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

โš ๏ธ Cautions

๐Ÿ”— Related Terms

WebSocket Streaming SSR REST API HTTP/2 Long Polling

๐Ÿ“š Learn More

๐Ÿ“„ MDN Web Docs - Server-sent events ๐Ÿ“„ WHATWG HTML Living Standard - SSE ๐Ÿ“„ MDN - EventSource API