0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ExpressでSSEを使ってみた

Last updated at Posted at 2025-05-18

SSE(Server-Sent Events)とは?

SSE(Server-Sent Events)は、サーバーからクライアントに向けて一方向にリアルタイムでデータを送信できる仕組みのこと。HTTPを使用しているためテキストでの通信となります。
リアルタイム性が必要な通知機能、コメントのライブフィード、LLMのストリーミングなどで使われるようです。

SSEの他にリアルタイムで通信する技術にWebSocketがあります。
WebSocketはクライアントとサーバー間の相互通信が可能なため、クライアントからサーバーに向けての通信も必要な場合はWebSocketを使いましょう。

実装

Express で1秒ごとに0からカウントした値をクライアントに送信するコードを書いてみます。

Expressサンプル

const express = require("express");
const app = express();

app.listen(3000, () => {
  console.log("Server is running on port 3000");
});

app.get("/event", (req, res) => {
  res.setHeader("Content-Type", "text/event-stream");
  res.setHeader("Access-Control-Allow-Origin", "*"); // CORS は任意で設定

  let counter = 0;

  const sendData = () => {
    res.write(`data: ${counter}\n\n`);
    counter++;
  };

  const interval = setInterval(sendData, 1000);

  req.on("close", () => {
    clearInterval(interval);
    res.end();
  });
});

こちらのサンプルでは、/event へリクエストしてきたクライアントに対して値を返しています。
SSE を使用するには MIME タイプを text/event-stream に設定しましょう。
またデータを返却するときは、先頭に data: と 末尾に \n\n をつける必要があります。
通信が終了したときは、res.end(); で HTTP レスポンスのプロセスを終了させましょう。

クライアントサンプル

const eventSource = new EventSource("http://localhost:3000/event");

eventSource.onmessage = (event) => {
  console.log(event.data);
};

eventSource.onerror = (err) => {
  console.error("Error", err);
};

クライアント側の実装も簡単です。EventSource に Express の情報を記載すると、onmessage イベントから受け取ったデータを取得することができます。
サンプルコードでは1秒おきに console.log で受け取った値を表示しています。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?