Serve WebP & AVIF from Sanity Without Double-Encoding
By Nayan Kyada · · 6 min read
Part of The Sanity + Next.js Guide
Sanity's image CDN and Next.js both offer automatic WebP and AVIF conversion. When you stack them naively — passing a Sanity URL through next/image without thinking — you end up with double-encoding: Next's optimisation layer fetches an image Sanity has already resized and compressed, re-encodes it, and caches the result under a cache key you can't easily predict. Here is the setup that avoids it.
Why double-encoding is a real problem
Next.js Image optimisation works by fetching the src URL you pass in, running it through Sharp (or the Vercel edge equivalent), and caching the result keyed on src + width + quality. If that src already points to an image Sanity's CDN has resized and compressed, Sharp receives an already-lossy file as input. It decodes it, loses some quality to generation loss, re-encodes it, and stores the result. The cached file can be larger than what Sanity would have served directly, and the /_next/image route adds a round-trip for every unique src string.
The practical symptoms are a slow LCP on first uncached load, extra image-optimisation usage and cache entries on your host, and confusing Lighthouse scores where the "serve images in modern formats" audit fires even though your CDN is already doing it.
Understanding Sanity's auto=format
Sanity's image URL builder exposes an auto('format') method. When you call it, the CDN reads the Accept header on the incoming request and returns AVIF or WebP when the client supports them (AVIF is generated asynchronously, so the first few requests may get WebP), falling back to the source format otherwise — same URL, content-negotiated response.
// lib/sanity-image.ts
import { createImageUrlBuilder, type SanityImageSource } from '@sanity/image-url'
import { client } from './sanity-client'
const builder = createImageUrlBuilder(client)
export function urlFor(
source: SanityImageSource,
width: number,
quality = 80
) {
return builder
.image(source)
.width(width)
.quality(quality)
.auto('format') // CDN negotiates AVIF/WebP/JPEG per Accept header
.url()
}The URL produced looks like:
https://cdn.sanity.io/images/<projectId>/<dataset>/abc123.jpg?w=800&q=80&auto=format
Notice the extension is still .jpg. The format decision happens at the edge, not in the URL. That matters for cache keys, which I'll explain below.
When to bypass next/image entirely
If the image is above-the-fold and you have exact width/height from Sanity metadata, you can skip next/image and render a plain <img> with a srcSet built from Sanity URLs. You lose next/image's built-in blur placeholder and have to set loading/fetchPriority yourself, but you gain:
- Zero Vercel image optimisation costs
- Sanity CDN cache hits instead of Vercel cache hits (better global PoP distribution)
- A stable, predictable URL for
<link rel="preload">
// components/SanityCdnImage.tsx
import { urlFor } from '@/lib/sanity-image'
import type { SanityImageSource } from '@sanity/image-url'
interface Props {
source: SanityImageSource
alt: string
width: number
height: number
priority?: boolean
}
const WIDTHS = [400, 800, 1200, 1600]
export function SanityCdnImage({ source, alt, width, height, priority }: Props) {
const srcSet = WIDTHS.map((w) => `${urlFor(source, w)} ${w}w`).join(', ')
const src = urlFor(source, width)
return (
<img
src={src}
srcSet={srcSet}
sizes="(max-width: 768px) 100vw, 800px"
alt={alt}
width={width}
height={height}
loading={priority ? 'eager' : 'lazy'}
decoding="async"
fetchPriority={priority ? 'high' : undefined}
/>
)
}This works well for hero images where you know width and height at build time from Sanity's asset.metadata.dimensions. For thumbnails in a grid where layout shifts are unlikely and you want lazy loading managed by the browser, this is all you need.
When to keep next/image in the pipeline
next/image is worth keeping for:
- Images served from a remote origin that isn't Sanity (user-uploaded avatars, partner logos)
- Cases where you want the automatic
blurplaceholder without rolling your own LQIP - Responsive images inside MDX or Portable Text where you don't control the render context
If you do use next/image with a Sanity src, decide which layer does the work. With the default loader, Next's optimiser fetches the src server-side (it doesn't forward the browser's headers), so auto=format does nothing useful there; pass the plain asset URL and let Next resize and pick the format. Mixing both just means Sanity compresses the image and Next compresses it again.
The cleaner approach for Sanity images is a custom loader. A loader replaces Next's optimiser entirely: the browser requests the URL your loader returns straight from Sanity's CDN, so Sanity does the resizing and format negotiation and nothing is re-encoded:
// lib/sanity-next-loader.ts
import type { ImageLoaderProps } from 'next/image'
export function sanityLoader({ src, width, quality }: ImageLoaderProps): string {
const url = new URL(src)
// The browser fetches this URL directly, so let Sanity negotiate the format
url.searchParams.set('auto', 'format')
url.searchParams.set('w', String(width))
url.searchParams.set('q', String(quality ?? 80))
return url.toString()
}Pass it as loader={sanityLoader} on any <Image> component that uses a Sanity CDN URL (or set it once with images.loaderFile in next.config). next/image still generates the srcset, lazy loading, and sizing, but there is no /_next/image request, no Sharp re-encode, and no Vercel image-optimisation usage; caching lives entirely on Sanity's CDN.
Cache key hygiene
Sanity's CDN caches on the full URL including query parameters. auto=format doesn't change the cache key because format selection is header-based at the Sanity edge — same URL, different response body per client. That means two users with different browser support hit the same Sanity URL and get format-appropriate responses without busting the cache.
Vercel's image cache, on the other hand, keys on the src string as passed to <Image>. If you route a Sanity URL through the default next/image optimiser, it caches its own re-encoded output per src, width, quality, and output format, and the browser only ever sees the /_next/image URL, never the Sanity one. Users still get a format their browser supports, because Next negotiates that itself. So it isn't broken, just wasteful: two layers of processing and two caches for the same image.
The rule I follow on every project
- Above-the-fold images with known dimensions: plain
<img>+ Sanity CDN +auto=format. Preload with<link rel="preload" as="image" imagesrcset="...">. - Below-the-fold images in grids or listings: same, but no preload.
next/imagewhen you need blur placeholders or are sourcing from a non-Sanity origin. For Sanity sources, use the custom loader so Sanity's CDN serves the image directly.
This keeps Sanity's CDN doing the format work it's already optimised for, avoids re-encoding overhead on Vercel, and gives you a clear mental model for where each image's cache lives.
Frequently asked questions
01Why does routing a Sanity auto=format image URL through next/image cause double-encoding?
Because next/image's default optimizer fetches whatever URL you give it, decodes it, and re-encodes it — so an image Sanity's CDN has already resized and compressed gets a second lossy encode, which costs quality to generation loss and can produce a *larger* file than Sanity would have served directly. Pick one layer to own resizing and format negotiation: either Sanity's CDN (a custom `loader` that returns Sanity URLs with `auto=format`, so the browser fetches from Sanity directly and Next's optimizer is skipped) or next/image's default optimizer (pass the plain Sanity asset URL without `auto=format` or resize params).
02Should I use a plain <img> tag or next/image for Sanity images?
Plain `<img>` with a manually built `srcSet` for above-the-fold images where you already know width and height from Sanity's `metadata.dimensions` — you skip Vercel's optimization cost entirely and get Sanity CDN cache hits with better global PoP distribution, at the cost of losing next/image's automatic blur placeholder. Keep `next/image` for anything sourced from a non-Sanity origin, or where you want the built-in blur-up without rolling your own LQIP handling.