How to validate uploaded files in Node JS

Validate uploaded files is a must in backend engineering. We won’t malicious file will be uploaded to our app. If we do not validate the uploaded files, it will be a backdoor to our app and permit hacker to insert malicious script file in our server.

How to validate uploaded files in Node JS? I will show a simple approach like below

const { files } = req;
const allowedFileTypes = ['image/png', 'image/jpeg', 'image/jpg'];      if(!allowedFileTypes.includes(files.propertyName.mimetype)) {
    response.messageTitle = "Invalid Document Format";
    response.message = "Make sure the document format is PNG/JPG/JPEG.";
    return response;

We can use mimetype property from files in node js request.

Leave a Comment