Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate base64 images in NodeJS/Express?

Let's say I am creating a REST API with Node/Express and data is exchanged between the client and server via JSON.

A user is filling out a registration form and one of the fields is an image input to upload a profile image. Images cannot be sent through JSON and therefore must be converted to a base64 string.

How do I validate this is indeed a base64 string of an image on the serverside? Or is it best practice not to send the profile image as a base64?

like image 944
Hayden Avatar asked Jan 02 '23 12:01

Hayden


2 Answers

You could start by checking if the string is a base64 image, with a proper mime type.
I found this library on npm registry doing exactly that (not tested).

const isBase64 = require('is-base64');
let base64str_img = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAoHBwgHBgoIC...ljA5GC68sN8AoXT/AF7fw7//2Q==';

console.log(isBase64(base64str_img, { mime: true })); // true

Then you can verify if the mime type is allowed within your app, or make other verifications like trying to display the image file and catch possible error.

Anyway, If you want to be really sure about user input, you have to handle it by yourself in the first place. That is the best practice you should care about.

like image 120
TGrif Avatar answered Jan 05 '23 15:01

TGrif


The Base64 value it is a valid image only if its decoded data has the correct MIME type, and the width and height are greater than zero. A handy way to check it all, is to install the jimp package and use it as follows:

var b64 = 'R0lGODdhAQADAPABAP////8AACwAAAAAAQADAAACAgxQADs=',
buf = Buffer.from(b64, 'base64');

require('jimp').read(buf).then(function (img) {
    if (img.bitmap.width > 0 && img.bitmap.height > 0) {
        console.log('Valid image');
    } else {
        console.log('Invalid image');
    }
}).catch (function (err) {
    console.log(err);
});
like image 20
Victor Avatar answered Jan 05 '23 14:01

Victor