next-http-proxy-middleware icon indicating copy to clipboard operation
next-http-proxy-middleware copied to clipboard

Change the Content-Length to actual size

Open SanskarDahiya opened this issue 3 years ago • 4 comments

I'm changing the body of request before httpProxyMiddleware function, & Server keep giving 400 Bad Request error.

Later I recognize that we also need to define the length of data before request. That's why I've added this code to set Content-Length to actual size again.

SanskarDahiya avatar Jul 26 '22 08:07 SanskarDahiya

Hi @SanskarDahiya

next-http-proxy-middleware passes the request (including headers) from the client to the server as is.

Therefore, the content-length header must be included in the client-side request.

I checked that content-length information was included in the Request header when uploading a file from a web browser, and the actual request received through the proxy also included a content-length header.

Please let me know if I'm misunderstanding anything.

Thanks :)

stegano avatar Jul 26 '22 14:07 stegano

Hi @stegano Yes, You are absolutely correct, But user didn't set Content-Length header, It implicitly set by library like axios / fetch or by browser.

In my scenario, I'm making a request with body {"_id":1,"user":"test"}. Then at proxy server, I'm adding new field into body {"_id":1,"user":"test","token":"14234"}. Now, At proxy, Data length has changed, but It uses same Content-Length header, & then at server, I'm unable to read complete data. At server I only read {"_id":1,"user":"test"," this part. Therefore, I have to explicitly change the Content-Length header to new length.

SanskarDahiya avatar Jul 27 '22 08:07 SanskarDahiya

@SanskarDahiya

Hi, again I understand your situation.

You can use onProxyInit option, try this

  • https://github.com/stegano/next-http-proxy-middleware#onproxyinit-option
// e.g.
import { NextApiRequest, NextApiResponse } from "next";
import httpProxyMiddleware from "next-http-proxy-middleware";

export default (req: NextApiRequest, res: NextApiResponse) =>
  httpProxyMiddleware(req, res, {
    onProxyInit: (proxy) => {
      proxy.on("proxyReq", (proxyReq) => {
        proxyReq.setHeader("Content-Length", Buffer.byteLength(req.body));
      });
    },
    target: "...",
    pathRewrite: [
      {
        ...
      },
    ],
  });

I recommend using the onProxyInit option rather than modifying this library. I'm not sure, but someone may need to intentionally omit the content-length header.

Thanks :)

stegano avatar Jul 27 '22 14:07 stegano

Got it. I'm currently doing the same.

Thank you for your response.

SanskarDahiya avatar Jul 27 '22 14:07 SanskarDahiya