Rang
Rang

Reputation: 13

Modifying response body from target proxy through http-proxy-middleware

I am trying to modify HTML body response of proxied target url, but my res.send method is not executing because onProxyRes function is not waiting the proxyRes.on('end', () => { event.

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();

const onProxyRes = async function  (proxyRes, req, res) {
  let body = '';
  proxyRes.on('data', (chunk) => {
    body += chunk;
  });

  proxyRes.on('end', () => {
    res.send(body + ' modified part'); // Send the modified response
  });
};

;(async() => {
  const exampleProxy = createProxyMiddleware({
    target: 'https://example.com',
    changeOrigin: true,
    on: { proxyRes: onProxyRes }
  });
  app.use('/', exampleProxy);
  
  app.listen(3000)
})()

output is the source code of https://example.com.

But if I update the function as,

const onProxyRes = async function  (proxyRes, req, res) {
  res.send('test'); // Send the modified response
};

I can set the response as test, but I need to set the response from actual target url's response body + my modifications.. any suggestions? thanks.

Upvotes: 1

Views: 144

Answers (1)

traynor
traynor

Reputation: 8717

To modify response, you need to use responseInterceptor method:

Intercept responses from upstream with responseInterceptor. (Make sure to set selfHandleResponse: true)
(...)
NOTE: responseInterceptor disables streaming of target's response.

https://www.npmjs.com/package/http-proxy-middleware#intercept-and-manipulate-responses

See example from the recipes:

Replace text and change http status code

const { createProxyMiddleware, responseInterceptor } = require('http-proxy-middleware');

const proxy = createProxyMiddleware({
  target: 'http://www.example.com',
  changeOrigin: true, // for vhosted sites

  /**
   * IMPORTANT: avoid res.end being called automatically
   **/
  selfHandleResponse: true, // res.end() will be called internally by responseInterceptor()

  /**
   * Intercept response and replace 'Hello' with 'Teapot' with 418 http response status code
   **/
  on: {
    proxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
      res.statusCode = 418; // set different response status code

      const response = responseBuffer.toString('utf8');
      return response.replaceAll('Example', 'Teapot');
    }),
  },
});

Upvotes: 0

Related Questions