Optimize Image Sizes with Next.js for Better Web Vitals

If you are using Next.js, you are likely using <Image />. But many developers misunderstand the sizes attribute, assuming it's used to style the image's physical dimensions on the screen. The sizes attribute actually tells the browser's preload parser how much of the viewport the image will take up at different breakpoints, before the CSS even loads. This allows the browser to download the perfectly sized image from the auto-generated srcset immediately. JavaScript <Image src="/hero.jpg" fill // "On desktop, it's 33vw. On tablets, 50vw. On mobile, 100vw." sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw" alt="Hero image" /> If you leave sizes out on responsive images, Next.js defaults to 100vw, forcing desktop users to download massive, bandwidth-heavy files for small thumbnail images. Fix your sizes, and watch your Core Web Vitals improve! #TypeScript #ReactHooks #CodingTips #FrontendEngineering #JavaScript"

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories