Search code examples
javascriptnode.jsexpressspam-preventionbusboy

How to prevent POST spamming in node.js Express using busboy?


I am following the example here: https://www.npmjs.com/package/busboy

I am worried that someone may deliberately try to overload the server. I wonder if there is a convenient way, before the data is uploaded, to prevent spamming by measuring the size of the entire POST body, not just the file(s) uploaded. I tried the following, which apparently didn't work:

if (JSON.stringify(req.body).length > 5 * 1024 * 1024) res.redirect('/');

Solution

  • You cannot rely on Content-Length being set. Even if it were set, if the person was acting malicious, they either may use an incorrect Content-Length or they may use Transfer-Encoding: chunked, in which case there is no way to tell how large the request body is.

    Additionally, calling stringify() every time on req.body could easily cause a DoS-style attack as well.

    However, busboy does have several options for limiting various aspects of application/x-www-form-urlencoded and multipart/form-data requests (e.g. max file size, max number of files, etc.).

    You might also limit the parsing of request bodies to routes where you're expecting request bodies, instead of trying to parse request bodies for all requests.