How to convert JPG images to WebP format in Sanity for frontend use?

2 replies
Last updated: Aug 15, 2023
In Sanity when using
image
how should an uploaded image of format
jpg
be converted to
webp
to be used as a background image on the frontend? Im not seeing under
asset
a way to grab a webp. Can this be converted in Sanity after upload?
AI Update

Yes, Sanity can absolutely convert JPG images to WebP (and other formats) after upload! You don't need to grab a specific WebP version from the asset object—instead, you transform the image URL using query parameters or the @sanity/image-url helper library.

Using URL Parameters Directly

You can add format parameters directly to any Sanity image URL:

https://cdn.sanity.io/images/[project-id]/[dataset]/[asset-id]-[dimensions].jpg?fm=webp

Or even better, use auto format detection which automatically serves WebP or AVIF to browsers that support them:

https://cdn.sanity.io/images/[project-id]/[dataset]/[asset-id]-[dimensions].jpg?auto=format

The auto=format parameter is particularly useful because it delivers the most efficient format based on the user's browser capabilities.

Using @sanity/image-url Builder

The cleaner approach is using the @sanity/image-url helper library. First, set up a builder:

import imageUrlBuilder from '@sanity/image-url'
import { client } from './sanity/client'

const builder = imageUrlBuilder(client)

export function urlFor(source) {
  return builder.image(source)
}

Then use it to build your WebP URLs:

// Explicit WebP format
const imageUrl = urlFor(image).format('webp').url()

// Or use auto format (recommended)
const imageUrl = urlFor(image).auto('format').url()

For a background image, you might combine this with width and quality settings:

const bgImage = urlFor(image)
  .width(1920)
  .auto('format')
  .quality(80)
  .url()

// Use in CSS
<div style={{ backgroundImage: `url(${bgImage})` }} />

How It Works

Sanity's Image Pipeline performs these transformations on-demand when the URL is first requested, then caches the result on their global CDN. The original JPG stays in your Content Lake unchanged, but you can request it in any supported format (WebP, AVIF, PNG, etc.) through URL parameters.

This means you don't need to store multiple versions of images—Sanity handles the conversion and optimization automatically!

Show original thread
2 replies
sanity doesn’t offer image conversions like that.
actually it does it seems. you just need append
auto=format
https://www.sanity.io/docs/image-urls#auto-777d41f23d56

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?