WebP Image Optimisation + BlurHash with Sharp in NodeJS

Learn to convert images to WebP and use BlurHash for placeholders, including resizing tips and code for optimizing web app visuals and load times.

WebP Image Optimisation + BlurHash with Sharp in NodeJS
Image Optimisation + Blurhash with Sharp in NodeJS

In this blog post, we'll cover how to convert images into WebP format and create blur hash images to store in your database to show as placeholders. WebP is used to create images that only need to be used in applications.

Resizing to Fit WebP

First, there's an important thing to note when using WebP. There is a maximum width and height of 16383 (according to Google, the creators of WebP - documented here).

If you forget to implement this you'll get a sharp error saying:

Processed image is too large for the WebP format

So we need to implement code to resize this if necessary before converting:

This code just does a quick check to see if it needs to be resized and returns the sharp instance if needed.

Notice that width and height are optional on the metadata. I haven't seen these values returned as undefined, but in the event an image is corrupted ensure to handle the errors.

Converting To WebP

Next, we convert the image to WebP. We'll make use of the function above to resize if needed.

This returns our converted image to WebP.

For more configuration read more about using Sharp here

Creating the BlurHash

We also want to create a BlurHash to store in our database for showing a placeholder while the image loads over the network.

This returns us the 36-character hashed string that can be used with BlurHash on the front end.

In our react front end we can use it like this:

Convert to fit your use case, but that's all you need to show blurred placeholders before your already optimised WebP image loads on the front end.

Read more about BlurHash usage here

Thanks for reading