Logo with initials

WebP and AVIF images with Gatsby

One of my favourite features of Gatsby is how you can use it to process your images. It can go from simple size optimisations to compression. Gatsby also allows you to use the not-so-new WebP image format.

If you’re using gatsby-plugin-image then you can access the WebP and AVIF versions of the image that you want by adding them to the formats array.

{
  childImageSharp {
    # Other options include width/height (set both width and height to crop),
    # grayscale, duotone, rotate, etc.
    gatsbyImageData(formats: [AUTO, WEBP, AVIF])
  }
}

If you’re not using gatsby-plugin-image, which is my case, you can still take advantage of WebP images by grabbing the WebP source file directly.

{
  image {
    id
    childImageSharp {
      # width, height and quality are optional
      fixed(width: 300, quality: 70) {
        srcWebp
        src
      }
    }
  }
}

Then use the <picture> element to serve WebP images to browsers that support it.

<picture>
  <source srcSet={image.srcWebp} type="image/webp" />
  <img src={image.src} alt="Book cover" loading="lazy" />
</picture>