Skip to content

options.on.proxyRes NOT work at req.headers.accept = text/event-stream on Koa2 #1101

Open
@axolo

Description

@axolo

Checks

Describe the bug (be clear and concise)

koa-router

const { createProxyMiddleware } = require('http-proxy-middleware');
const convert = require('koa-connect');

module.exports = app => {
  const { router, config } = app;

  const proxy = createProxyMiddleware({
    target: config.dify.baseUrl,
    changeOrigin: true,
    ws: true,
    timeout: 0,
    pathRewrite: { '^/dify': '' },
    headers: {
      Authorization: 'Bearer ' + config.dify.apiKey,
    },
    on: {
      proxyReq: (proxyReq, req) => {
        console.log('proxyReq:', req.headers.accept); // text/event-stream
      },
      proxyRes: (proxyRes, req) => {
        // ONLY req.headers.accept = text/event-stream NOT work
        console.log('proxyRes:', req.headers.accept);
        if (req.headers.accept === 'text/event-stream') {
          proxyRes.headers['Content-Type'] = 'text/event-stream; charset=utf-8';
          proxyRes.headers['Cache-Control'] = 'no-cache';
          proxyRes.headers.Connection = 'keep-alive';
        }
      },
    },
  });

  router.all(/^\/dify/, async (ctx, next) => {
    await convert(proxy)(ctx, next);
  });
};

Step-by-step reproduction instructions

1. client use @microsoft/fetch-event-source fetchEventSource POST /chat-messages
2. on.proxyReq console.log proxyReq: text/event-stream
3. on.proxyRes console.log not work and client fetch 504 timeout error
4. client use fetch GET /info, work good, on.proxyReq and on.proxyRes console.log accept application/json

Expected behavior (be clear and concise)

client request accept text/event-stream by EventSource and server streaming output event message from sse

How is http-proxy-middleware used in your project?

reader-api@0.18.2 D:\Projects\reader-api
└── http-proxy-middleware@3.0.5

What http-proxy-middleware configuration are you using?

see koa-router

What OS/version and node/version are you seeing the problem?

Windows 11 10.0.26100 x64
Node: 22.14.0
Edge: Chromium (133.0.3065.69)

Additional context (optional)

No response

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions