HeadlinesBriefing favicon HeadlinesBriefing.com

Fix Next.js Image Performance with Sanity.io

DEV Community •
×

A developer deploying a blog to Vercel discovered their Lighthouse performance score was below 80. The culprit was unoptimized images from their Sanity.io backend. Simply plugging image URLs into the default Next.js component wasn't cutting it, leading to oversized assets that hurt load times and user experience.

To solve this, they built a custom workflow connecting Next.js with Sanity’s CDN. The solution involves configuring Next.js to prioritize modern formats like AVIF and creating utility functions to handle image URLs. This setup leverages Sanity's powerful image pipeline instead of forcing Next.js to re-process everything.

The core of the fix is a custom `SanityImage` wrapper component and a specific loader. This loader tells Next.js how to request correctly sized images directly from Sanity based on viewport width. It also respects crops and hotspots defined in the Sanity Studio, ensuring visual fidelity without the performance penalty.

Finally, implementing the `sizes` attribute was the missing piece for a responsive grid. By defining exact viewport widths, the browser stops downloading massive images for small containers. This single change reportedly dropped network payloads by over 60%, proving that proper configuration is key to hitting that perfect 100 on Lighthouse.