Here, we are going to discuss about securing our Node Express application if any unwanted user tries to impact performance of our application by sending a very huge input JSON data or by uploading a very large file.
Generally, Express allows 100KB JSON data by default. If we try to input more than 100KB JSON data, it will return 413 error code. In case of file uploading by using Multer package, there is not any defult file size limit. So, in can case of file uploading, we should apply some file size limit in Node Js code. Lets discuss about JSON input data and file uploading separately.
JSON input data: As told above, Express allows by default 100KB JSON data which is pretty good in most of the scenarios. If in some scenarios, we need to send JSON data of size more than 100KB, then we have to increase the default JSON data size limit. We can achieve it by using the below two middlewares.
Now, this express application will allow us to send JSON data of up to 10mb size.
File upload size limit: Generally, we use Multer package to upload incoming files. Here, we can restrict the security threat by providing the max file size limit in multer. It can be done in the following way.
Here, we are defining the maximum allowed file size limit as 150mb. This size applies for both single file upload and multiple file upload. So, if we are uploading a single file of size say 200mb or two files together with each file having size about 100mb that is 100+100=200mb then, in both the cases, the file size limit is exceeding the defined file size that is 150mb. So, in these cases, it will give error with 500 status code with error message as "File too large".
I have created below two routes for handling single file upload and multiple file upload.
Here, I am giving my code that will help in reproducing the outcome of above discussion.
package.json
app.js
No comments:
Post a Comment
Please provide your precious comments and suggestion