3

With Nextjs the expected outcome is to see the Image component rendered as .WebP or .AVIF but it remains jpg -

enter image description here

Below is my next.config.js

/** @type {import('next').NextConfig} */
module.exports = {
  images: {
    domains: ['cdn.sanity.io'],
    formats: ['image/avif', 'image/webp'],
  },
  reactStrictMode: true,
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/,
      use: [{ loader: '@svgr/webpack', options: { icon: true } }],
    });
    return config;
  }, };

The following is the next/image component:

   <Image
                          className="kitchen-img"
                          loader={myLoader}
                          loading="lazy"
                          layout="fill"
                          objectFit="cover"
                          src={urlFor(kitchen.mainImage).url()!}
                          alt={kitchen.title}
                        />

Any idea why the it doesn't come up as avif/webp? What am I missing?

const myLoader = ({ src, width, quality }: any) => {
return `${src}?w=${width}&q=${quality || 85}`  };
juliomalves
  • 42,130
  • 20
  • 150
  • 146
Enadot
  • 107
  • 3
  • 9
  • 2
    Could you share with us your loader (myLoader)? It seems like you trigger the image directly for your CDN, and is not stored in the next cache folder. – Elisei Nicolae Jun 12 '22 at 12:17
  • Hi Nicolae, thank your for trying to help, I've added the code of the loader above. any ideas? – Enadot Jun 12 '22 at 19:31

1 Answers1

4

In your case, you are using a loader that will trigger the images directly from your CDN, and will not be stored in next cache folder.

To be 100% sure, try to remove the loader={myLoader} and check the network :) again. (test with next dev, and check if your image has webp extension)

If you still want to use webp, check if you can send the extension via your CDN.

const myLoader = ({ src, width, quality }: any) => {
  return `${src}?w=${width}&q=${quality || 85}&?fm=webp`
};

Keep in mind, that some browsers don't support webp.

Elisei Nicolae
  • 293
  • 2
  • 12
  • Bingo. when removing the loader it rendered as avif. Thank you – Enadot Jun 13 '22 at 08:10
  • BTW, adding &?fm=webp will get this only webp format not avif. so what's the best practice to let it choose randomly either webp or avif using this method? – Enadot Jun 13 '22 at 08:12
  • 1
    Currently, I don't have a solution for that. What you need to do, is to make a function that checks if avif / webp are compatible. – Elisei Nicolae Jun 13 '22 at 11:12