Optimizing Images for the Web: The Importance of Using WebP and Best Practices for SEO

Optimizing Images for the Web: The Importance of Using WebP and Best Practices for SEO

Convert images to the WebP format using Node.js and improve your website's performance and discoverability through image optimization best practices.

Play this article


Search engine optimization, or SEO, is a crucial aspect of running a website. One of the most important things to consider when optimizing a website for search engines is image optimization. In this blog post, we will cover a technique to optimize images for the web called WebP, and how to convert images to this format using the sharp library in Node.js.

What is WebP and why should you use it?

WebP is a modern image format developed by Google that provides lossless and lossy compression for images on the web. It provides superior compression compared to other popular image formats like JPEG and PNG. This means that images in WebP format are smaller in size, which leads to faster loading times and a better user experience. Additionally, WebP images are supported by most modern web browsers, including Google Chrome, Firefox, and Microsoft Edge.

How to convert images to WebP using the sharp library

The sharp library is a popular image processing library for Node.js that can be used to convert images to the WebP format. In the example code provided, the script reads the contents of the specified input directories and checks if the files are in JPEG or PNG format. If so, it uses the sharp library to convert the image to the WebP format and set the quality to 85. The optimized images are then saved to the same directory with the same file name but with a .webp extension.

Optimizing images for SEO

In addition to converting images to the WebP format, there are several other steps you can take to optimize images for SEO. These include:

  • Compressing images to reduce their file size

  • Using descriptive and relevant file names for images

  • Adding alt text to images to describe their content for search engines

  • Using image sitemaps to inform search engines about images on your website

Now Lets, Code step by step

  • Create a new directory for your project and navigate into it in the terminal.

  • Run the command npm init -y to initialize a new npm project. This will create a package.json file in your project directory.

  • Run the command npm install sharp to install the sharp library, which is used to optimize images in this script.

  • Run the command npm install fs to install the fs library, which is used to read the input directory and files in this script.

  • Create a new file called index.js in your project directory.

  • In the index.js file, add the following code:

      const sharp = require("sharp");
      const fs = require("fs");
  • Next, add the following code to define the input directories that the script will look for images in:

      const inputDirs = ["./images", "./img"];
      // You can change the input directories to match the directories where your images are located.
  • Create an async function called optimize to handle the image optimization:

      const optimize = async () => {
        for (const inputDir of inputDirs) {
          // Read input directory
          fs.readdir(inputDir, (err, files) => {
      // This function loops through each of the input directories and uses the fs.readdir method to read the contents of the directory.
  • Within the optimize function, add a check for an error when reading the input directory:

      javascriptCopy code      if (err) {
              console.log(`Error reading directory: ${err}`);
            } else {
      // If an error occurs, it will be logged to the console.
  • In the else block, use a for loop to iterate over the files in the input directory:

              for (const file of files) {
  • Inside the for loop, add a check to see if the file is a JPG, JPEG, or PNG file:

                if (
                  file.endsWith(".jpg") ||
                  file.endsWith(".jpeg") ||
                ) {
  • If the file is a JPG, JPEG, or PNG, use the sharp library to convert the file to webp and set the quality to 85:

                  // Read input file
                  const inputFile = `${inputDir}/${file}`;
                    .webp({ quality: 85 }) // Convert to webp and set quality to 85
  • Use the toFile method to save the optimized image to the input directory:

  • Add a then block to log a message to the console once the image has been optimized:

                    .then(() => {
                      console.log(`Optimized ${file}`);
  • The catch block will catch any errors that occur when trying to optimize the image using the Sharp library.

      .catch((err) => {
                      console.log(`Error optimizing image: ${err}`);

This block of code will log a message to the console if there is an error while trying to optimize the image. The message will include the error that occurred, so it can be easily troubleshot.

  • Finally, the script checks if it is being run as the main module.

      if (require.main === module) {

This allows the script to be imported as a module into other scripts, but only run when called as the main script. This means that if the script is imported as a module into another script, the optimize() function will not be called.

  • Save the file, and run the script by running node index.js in the terminal. The script will read the images directory and optimize all images in the directory, converting them to webp format and setting the quality to 85.

Full Code - https://github.com/aadrshkashyp/webp-Converter-with-JavaScript

In summary,

This script uses the npm packages "sharp" and "fs" to optimize and convert images in a specified directory to webp format. It first imports the two packages, and then defines an async function called "optimize." The function loops through an array of input directories, reads the directory, and for each image file found, it is opened using the sharp package and then converted to webp format with a quality setting of 85. The optimized image is then saved to the same directory with a .webp file extension. If there are any errors encountered during the process, such as reading the directory or optimizing the image, the script will log an error message to the console. The script is then run by checking if it is the main module being called. This script can be useful for optimizing images in bulk, such as for a website or application, to improve load times and save storage space.


In conclusion, WebP is a powerful image format that can significantly improve the performance of your website by providing smaller image sizes and faster loading times. By using the sharp library in Node.js, it is easy to convert existing images to the WebP format. Additionally, by following best practices for image optimization, you can improve the SEO of your website and make it more discoverable by search engines.

Did you find this article valuable?

Support Aadarsh Kashyap by becoming a sponsor. Any amount is appreciated!