できない.dev

Express「Cannot set headers after they are sent to the client」の原因と直し方

Express の Cannot set headers after they are sent to the client は、1 つのリクエストに 2 回応答すると出る。
応答した直後に return するか、res.headersSent で送信済みかを確かめれば直る。

公開: 更新:

症状できない · exit 7
curl -s http://localhost:3000/ping

2026-11-07 に node:22(Express 5.3.0 / Node.js 22.23.4) で実際に打って取った出力。検証環境の詳細

要約

Express のハンドラーが、すでに応答を送ったリクエストに res.json() や res.send() をもう一度呼ぶと、Node.js がヘッダーの再設定を拒んで例外を投げる。
Express 5.3.0(Node.js 22.23.4)では、サーバーのログに次の表示が出た。

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (node:_http_outgoing:700:11)
    at ServerResponse.header (/w/node_modules/express/lib/response.js:685:10)
    at ServerResponse.send (/w/node_modules/express/lib/response.js:141:14)
    at ServerResponse.json (/w/node_modules/express/lib/response.js:249:15)
    at /w/app.js:7:7

クライアントには最初の応答が届いているので、ブラウザや curl だけを見ていると気付きにくい。
スタックトレースの中の自分のファイルの行が、2 回目に応答した場所である。

実行例

node:22 の Express 5.3.0 で、return の無い 400 と応答後の next() を含むアプリを起動すると、どちらの経路でもログに ERR_HTTP_HEADERS_SENT が出た。
setTimeout の中の 2 回目の応答ではプロセスが終了し、次の curl は終了コード 7 で失敗した。
return を付けて next() をやめた版では、ログにエラーが出なかった。

$ node app.js > server.log 2>&1 &
$ curl -s -i http://localhost:3000/items
HTTP/1.1 400 Bad Request
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 26
ETag: W/"1a-DsQP/+HU29pEiHuZ2uPQY67a6To"
Date: Sat, 07 Nov 2026 00:09:04 GMT
Connection: keep-alive
Keep-Alive: timeout=5
 
{"error":"id is required"}
$ curl -s -i http://localhost:3000/legacy
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 5
ETag: W/"5-4JlqN8E9RMOwYHSTnUP6N1m9MsE"
Date: Sat, 07 Nov 2026 00:09:04 GMT
Connection: keep-alive
Keep-Alive: timeout=5
 
first
$ cat server.log
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (node:_http_outgoing:700:11)
    at ServerResponse.header (/tmp/tmp.atwmf1QVGG/node_modules/express/lib/response.js:685:10)
    at ServerResponse.send (/tmp/tmp.atwmf1QVGG/node_modules/express/lib/response.js:141:14)
    at ServerResponse.json (/tmp/tmp.atwmf1QVGG/node_modules/express/lib/response.js:249:15)
    at /tmp/tmp.atwmf1QVGG/app.js:10:7
    at Layer.handleRequest (/tmp/tmp.atwmf1QVGG/node_modules/router/lib/layer.js:152:17)
    at next (/tmp/tmp.atwmf1QVGG/node_modules/router/lib/route.js:157:13)
    at Route.dispatch (/tmp/tmp.atwmf1QVGG/node_modules/router/lib/route.js:117:3)
    at handle (/tmp/tmp.atwmf1QVGG/node_modules/router/index.js:435:11)
    at Layer.handleRequest (/tmp/tmp.atwmf1QVGG/node_modules/router/lib/layer.js:152:17) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (node:_http_outgoing:700:11)
    at ServerResponse.header (/tmp/tmp.atwmf1QVGG/node_modules/express/lib/response.js:685:10)
    at ServerResponse.send (/tmp/tmp.atwmf1QVGG/node_modules/express/lib/response.js:141:14)
    at /tmp/tmp.atwmf1QVGG/app.js:19:19
    at Layer.handleRequest (/tmp/tmp.atwmf1QVGG/node_modules/router/lib/layer.js:152:17)
    at trimPrefix (/tmp/tmp.atwmf1QVGG/node_modules/router/index.js:342:13)
    at /tmp/tmp.atwmf1QVGG/node_modules/router/index.js:297:9
    at processParams (/tmp/tmp.atwmf1QVGG/node_modules/router/index.js:582:12)
    at next (/tmp/tmp.atwmf1QVGG/node_modules/router/index.js:291:5)
    at next (/tmp/tmp.atwmf1QVGG/node_modules/router/lib/route.js:132:14) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
$ node app.js > server.log 2>&1 &
$ curl -s http://localhost:3000/late
first
$ cat server.log
node:_http_outgoing:700
    throw new ERR_HTTP_HEADERS_SENT('set');
    ^
 
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (node:_http_outgoing:700:11)
    at ServerResponse.header (/tmp/tmp.atwmf1QVGG/node_modules/express/lib/response.js:685:10)
    at ServerResponse.send (/tmp/tmp.atwmf1QVGG/node_modules/express/lib/response.js:141:14)
    at Timeout._onTimeout (/tmp/tmp.atwmf1QVGG/app.js:8:24)
    at listOnTimeout (node:internal/timers:585:17)
    at process.processTimers (node:internal/timers:521:7) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
 
Node.js v22.23.4
$ curl -s http://localhost:3000/ping
$ echo $?
7
$ node app.js > server.log 2>&1 &
$ curl -s -i http://localhost:3000/items
HTTP/1.1 400 Bad Request
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 26
ETag: W/"1a-DsQP/+HU29pEiHuZ2uPQY67a6To"
Date: Sat, 07 Nov 2026 00:09:06 GMT
Connection: keep-alive
Keep-Alive: timeout=5
 
{"error":"id is required"}
$ curl -s -i http://localhost:3000/legacy
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 5
ETag: W/"5-4JlqN8E9RMOwYHSTnUP6N1m9MsE"
Date: Sat, 07 Nov 2026 00:09:06 GMT
Connection: keep-alive
Keep-Alive: timeout=5
 
first
$ curl -s "http://localhost:3000/items?id=7"
{"id":"7"}
$ cat server.log

— 2026-11-07 時点の出力

検証環境Node.js 22.23.4 / npm 10.9.9 / Python 3.11.2 / 2026-11-07 検証(ほか 2 件)
検証日
実行環境
node:22 Debian GNU/Linux 12 (bookworm)
バージョン
  • Node.js 22.23.4
  • npm 10.9.9
  • Python 3.11.2
  • Git 2.39.5
  • Express 5.3.0

この記事の「実行例」は、上記の環境で実際にコマンドを実行して得られた出力をそのまま掲載しています。 再現手順はリポジトリの検証スクリプトとして管理し、定期的に再実行して出力を更新しています。

解決策

1. 応答する行で return する

app.get("/items", (req, res) => {
  if (!req.query.id) {
    return res.status(400).json({ error: "id is required" });
  }
  res.json({ id: req.query.id });
});

return を付けると、id の無いリクエストは 400 だけを返し、ログにエラーが出なくなった。

2. 応答したら next() を呼ばない

ミドルウェアは「自分で応答する」か「next() で次へ渡す」のどちらか一方にする。
後ろの処理が送信済みかどうかを知る必要があるときは、res.headersSent(新しいタブで開く) を見る。

app.use((req, res) => {
  if (res.headersSent) return;
  res.status(404).send("not found");
});

自作のエラーハンドラーでは、送信済みなら next(err) で Express の既定のエラーハンドラーに任せる。
既定のハンドラーは接続を閉じてリクエストを失敗させる。

3. 非同期の処理は await してから 1 回だけ応答する

コールバックや then の中と、ハンドラーの末尾の両方で応答していないかを探す。
async のハンドラーにして結果を await し、応答を最後の 1 か所にまとめると、2 回目の応答が起きる経路が無くなる。

よくある原因

  1. 応答したあとに return していない。
    下のコードは id が無いとき 400 を返すが、関数を抜けないので、その後ろの res.json() も実行される。

    app.get("/items", (req, res) => {
      if (!req.query.id) {
        res.status(400).json({ error: "id is required" });
      }
      res.json({ id: req.query.id });
    });
  2. 応答したあとに next() を呼んでいる。
    後ろにある 404 のハンドラーが res.status(404).send() を呼び、同じエラーになった。

  3. 非同期の処理から遅れて応答している。
    setTimeout の中で 2 回目の res.send() を呼ぶと、例外が Express の外で起きるのでプロセスごと終了した。
    その後の接続はすべて失敗する。