最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - Why is my Server-Sent Events (SSE) connection delayed or not working with Nginx Ingress? - Stack Overflow

programmeradmin3浏览0评论

I am using Server-Sent Events (SSE) in a React frontend with a Node.js backend. SSE works perfectly when calling the API directly (e.g., via curl or direct browser request), but when routing through Nginx Ingress in Kubernetes, messages are:

Delayed (batching instead of real-time updates) Not received at all until the connection is closed

Disabling chunked transfer encoding (nginx.ingress.kubernetes.io/chunked_transfer_encoding: "off") Turning off proxy buffering (nginx.ingress.kubernetes.io/proxy-buffering: "off") Setting headers manually (X-Accel-Buffering: no) Checking network requests in DevTools

Setup Details Backend: Node.js with Express (res.write(), res.end()) Frontend: React with EventSource (new EventSource(...)) Ingress Controller: Nginx Ingress for Kubernetes

Despite all this, SSE messages are still not delivered in real-time.

Solution: Use res.flush() in Node.js The key problem was that Ingress Nginx buffers responses by default, delaying SSE messages. The solution was to explicitly flush the response stream using res.flush().

app.get("/events", (req, res) => {
  res.setHeader("Content-Type", "text/event-stream");
  res.setHeader("Cache-Control", "no-cache");
  res.setHeader("Connection", "keep-alive");
  res.setHeader("X-Accel-Buffering", "no"); // Important for Nginx

  setInterval(() => {
    res.write(`data: ${JSON.stringify({ message: "Hello", time: new Date() })}\n\n\`);
    res.flush(); // 
发布评论

评论列表(0)

  1. 暂无评论