next.jswebpnextjs-imageimage-optimizationimage-rendering

Why my Nextjs <Image> component renders as jpg instead of Webp or Avif?


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}`  };

Solution

  • 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.