Changing Next/Image to use Avif instead of just WebP

Originally published: 4 January 2024

Avif isn't *universally* supported, but it is widely adopted now

avif

Serving AVIF Images with Next.js for Max Performance

If you’re trying to optimize a Next.js site for maximum performance like I am, image formats are critical. Next’s Image component makes images seamless, but limiting us to basic formats like JPG and PNG. For top scores, we need next-gen formats like AVIF.

In my ongoing quest for 100% perfect page speed scores, I realized my image optimization was still lacking. My previous optimizations got me good scores, but AVIF could take me even further.

The Case for AVIF

AVIF is an emerging image format that offers major advantages over older formats:

The downsides are minimal browser support and lack of editing software support. But with Chrome, Firefox, and Safari on board, AVIF works for most users already.

So for a site pursuing ultimate performance like mine, AVIF is a no-brainer for supported browsers. JPGs can serve as a fallback where needed.

Enabling AVIF in Next.js

Next’s Image component doesn’t support AVIF out of the box, but adding it is straightforward.

In next.config.js, we can define the formats array:


images: {
  formats: ['image/avif', 'image/webp']
}

This tells Next to also look for and serve AVIF and WebP files when available.

To actually generate AVIF images, I used the sharp library. When saving my images, I save PNG, SVG, JPG, WebP, and AVIF versions to use across the site.

With those two changes, Next will automatically serve AVIF images to supported browsers for huge performance gains, and WebP when AVIF isn’t supported!

Here is the relevant part of my next.config.js for reference:

const withMDX = require('@next/mdx')({
  extension: /\.mdx?$/ 
});

module.exports = withMDX({
  images: {
    formats: ['image/avif', 'image/webp']  
  },
  
  // Rest of config
})

The Results

After deploying these AVIF changes, my speed scores got even better:

With WebP

speed with webp

With AVIF

speed with avif

Page weight also dropped by over 300 KB by replacing JPGs with AVIFs.

While AVIF isn’t yet universally supported, the performance benefits for modern browsers are tremendous.

Going Beyond Images

Images are just one part of a high performance site. Some other optimizations I’ve been exploring:

Like AVIF, these are a few more tools in my quest for 100% optimization. Each tweak gets me incrementally closer to perfection.

The pursuit of performance never ends, but supporting next-gen formats like AVIF gets us noticeably closer to loading nirvana. I’m thrilled to see my little Next.js site continue to get faster!

Read Count: 0


⬅️ Previous Post

Making this website and my future plans for it

Next Post ➡️

Comparing CDNs with a fresh Next.js app - quick look