Rendering images in Next.js with next-sanity
Reference for the Image component and imageLoader exported from next-sanity/image. Pass image objects or CDN URLs, apply the studio crop and hotspot, infer dimensions, and add blur placeholders.
The next-sanity library exports an Image component that renders images from the Sanity image CDN through the Next.js next/image component. Pass an image field from a GROQ query as the src prop, and the component applies the crop and hotspot set in the studio, infers the image dimensions, and serves right-sized, auto-formatted images for every srcSet width. It also exports imageLoader, for when you use next/image directly.
Image and imageLoader are alpha APIs and may change.
Installation
Passing an image object or asset ID to Image requires next-sanity 13.5.0 or later. Earlier versions, from 8.3.0, accept only a URL string. next-sanity 13 requires Next.js 16, React 19.2.3 or later, and sanity 5.29.0 or later.
From 13.5.0, next-sanity depends on @sanity/image-url itself, so you only need to install that package if you build image URLs yourself.
npm install next-sanity@latestpnpm add next-sanity@latestyarn add next-sanity@latestbun add next-sanity@latestRender an image field
Query the image field, then pass it to Image as src together with your project ID and dataset. The component builds the image CDN URL from the asset reference in the image object.
import { defineQuery } from 'next-sanity'
import { Image } from 'next-sanity/image'
import { dataset, projectId } from '@/sanity/env'
import { sanityFetch } from '@/sanity/lib/live'
const POST_QUERY = defineQuery(`*[_type == "post" && slug.current == $slug][0]{
title,
mainImage
}`)
export default async function PostPage({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { data: post } = await sanityFetch({ query: POST_QUERY, params: await params })
if (!post?.mainImage) return null
return (
<Image
src={post.mainImage}
projectId={projectId}
dataset={dataset}
width={800}
height={400}
alt={post.title ?? ''}
/>
)
}When src is an image object, the component:
- Applies the crop the editor set in the studio.
- Positions the crop around the hotspot when the
widthandheightyou request have a different aspect ratio from the cropped image. - Keeps the same crop for every width in the generated
srcSet.
src accepts the image shapes that sanity typegen generates: image objects with an asset reference, dereferenced asset documents, and bare image asset IDs (image-…). Missing crop and hotspot values fall back to the @sanity/image-url defaults. Stega-encoded characters from Visual Editing are stripped from the asset ID and URL automatically, so don't call stegaClean on the image first.
Read the project ID and dataset from the asset URL
If the query dereferences the asset URL, Image reads the project ID and dataset from it, and you can leave out both props:
*[_type == "post" && slug.current == $slug][0]{
title,
mainImage{
crop,
hotspot,
asset->{_id, url}
}
}<Image src={post.mainImage} width={800} height={400} alt={post.title ?? ''} />When neither the props nor the asset URL provide them, the component throws a TypeError: Unable to resolve the Sanity project id and dataset for the image. Pass the `projectId` and `dataset` props, or dereference the asset URL in the query (e.g. `asset->{url}`) so they can be read from it.
To avoid passing the project ID and dataset on every image, wrap the component once in your app:
import { Image as SanityImage, type ImageProps } from 'next-sanity/image'
import { dataset, projectId } from '@/sanity/env'
export function Image(props: ImageProps) {
return <SanityImage projectId={projectId} dataset={dataset} {...props} />
}Leave out the width and height
Unlike next/image, width and height are optional. When you leave them out, Image infers them, in this order, from:
- The
wandhparameters in the image URL, for example from an@sanity/image-urlbuilder. - The
rectcrop parameter in the URL, which includes the studio crop for image objects. - The original dimensions that Sanity encodes in every asset filename.
If you set only one of width or height, the component derives the other from the image's aspect ratio, the same way next/image does for static imports. This renders the image at the aspect ratio the editor chose:
<Image src={post.mainImage} width={800} alt={post.title ?? ''} />Fill a container and keep the hotspot in frame
With the fill prop, the browser crops the image to its parent element. When src is an image object with a hotspot, object-position defaults to the hotspot, so object-fit: cover keeps the subject in frame. A hotspot at x: 0.75, y: 0.25 becomes 75% 25%, adjusted for any studio crop.
<div style={{ position: 'relative', aspectRatio: '1 / 1' }}>
<Image
src={post.mainImage}
projectId={projectId}
dataset={dataset}
fill
sizes="50vw"
style={{ objectFit: 'cover' }}
alt={post.title ?? ''}
/>
</div>A hotspot outside the crop is pinned to the nearest edge. If you flip the image with queryParams={{ flip: 'h' }} (or v, or hv), the default position is mirrored to match. Set style.objectPosition or the objectPosition prop to override the default.
Show a blur placeholder
With placeholder="blur", Image uses the image's low-quality image preview (LQIP) as the placeholder when the query includes it. You don't need to set blurDataURL. Keep the asset's url or _id next to the metadata when you dereference the asset, so the component can still build the image URL:
*[_type == "post" && slug.current == $slug][0]{
title,
mainImage{
crop,
hotspot,
asset->{_id, url, metadata{lqip}}
}
}<Image src={post.mainImage} width={800} placeholder="blur" alt={post.title ?? ''} />If you also pass a blurDataURL prop, it takes precedence over the LQIP.
Add image transformations
Use the queryParams prop to add other image transformation parameters to the image URL, such as blur or saturation:
<Image src={post.mainImage} width={800} queryParams={{ blur: 50, sat: -100 }} alt="" />queryParamsignores the sizing parametersw,h, andrect. The image size comes from thewidthandheightprops, the URL, and the crop and hotspot.- For image objects and asset IDs,
fit, the crop mode (crop), and a focal point (fp-xwithfp-y) are passed to the URL builder before it computes the crop, so they change which part of the image you get.
An unsupported fit or crop value throws a TypeError, for example: Invalid `queryParams.fit` value "cover". Expected one of: clip, crop, fill, fillmax, max, scale, min.
Type image fields with TypeGen
next-sanity/image re-exports three helpers from @sanity/image-url for typing images from sanity typegen query results:
InferImageValue<T>: collects every image shape inT, which can be a query result type, a union of query results, or a schema type. It accepts both stega-branded results fromsanityFetchand clean results.InferStrictImageValue<T>: the same, limited to images that have an asset.isImageWithAsset: narrows an image value to one that has an asset.
import type { POST_QUERY_RESULT } from '@/sanity.types'
import { Image, isImageWithAsset, type InferImageValue } from 'next-sanity/image'
import { dataset, projectId } from '@/sanity/env'
type PostImageValue = InferImageValue<POST_QUERY_RESULT>
export function PostImage({
image,
alt,
}: {
image: PostImageValue | null | undefined
alt: string
}) {
if (!image || !isImageWithAsset(image)) return null
return (
<Image
src={image}
projectId={projectId}
dataset={dataset}
width={800}
height={400}
alt={alt}
/>
)
}How this differs from the next/image component
The Image component from next-sanity/image wraps next/image, so you get the same developer-facing features: lazy loading, srcSet generation, preloading, and layout stability. The difference is in where and how image optimization happens.
With the next-sanity/image component, the built-in loader bypasses the Next.js optimization proxy entirely. Instead, it constructs a URL that points directly to Sanity's image CDN with the right transformation parameters. Sanity's CDN handles resizing, format conversion, and caching at the edge. This means:
- No
remotePatternsconfiguration is needed innext.config.jsfor Sanity images. - Format negotiation (WebP, AVIF) happens at the CDN level through the
auto=formatparameter, based on the browser'sAcceptheader. - Your Next.js server doesn't process the images, reducing its CPU and memory load.
- The loader automatically maintains aspect ratio across
srcSetbreakpoints by recalculating thehparameter proportionally for each width. - The loader sets sensible defaults for the
fitparameter:fit=maxwhen only width is specified (prevents upscaling),fit=minwhen both width and height are present.
There are a couple of tradeoffs. src must be a Sanity image CDN URL, an image object, or an image asset ID, so static imports aren't supported. data: and blob: URLs are passed through unchanged and render unoptimized, as they do with next/image. The component also disallows the loader prop, since it ships with its own. If you need a custom loader or want to use the default Next.js optimization proxy, use next/image directly.
How the loader works
The built-in imageLoader transforms the Sanity CDN URL for each entry in the generated srcSet. For every width that next/image requests, the loader:
- Sets
auto=formatso the CDN returns the best format the browser supports (WebP, AVIF). See Image transformations for the full list of URL parameters. - Sets
fit=maxwhen only width is specified, orfit=minwhen both width and height are present. If the URL already contains afitparameter, the loader respects it. - Recalculates
hproportionally when bothwandhare present, preserving the original aspect ratio at each breakpoint. - Sets
wto the width thatnext/imagerequests. - Passes the
qualityprop through as theqURL parameter.
This means your images are served in the optimal format and size without additional configuration.
Props
ImageProps extends all next/image props except loader, and replaces src with the Sanity image sources described below.
Requiredsrc
string | object
The image to render. One of:
A Sanity image CDN URL, for example from
asset->urlor an@sanity/image-urlbuilder.An image object from a GROQ query (
{asset, crop, hotspot}). The studio crop and hotspot are applied. Requires 13.5.0 or later.An image asset ID (
image-…). Requires 13.5.0 or later.If a string
srcisn't a valid absolute URL, the component throws aTypeError:The `src` prop must be a valid URL to an image on the Sanity Image CDN.projectId
string
The project the image belongs to. Used with
datasetto build the URL whensrcis an image object or asset ID. Optional when the query dereferences the asset URL (asset->{url}). Requires 13.5.0 or later.dataset
string
The dataset the image belongs to. See
projectId. Requires 13.5.0 or later.width
number
Width in pixels. Appended as
wto the URL and used by the loader for aspect ratio calculations. Optional from 13.5.0: when omitted, it's inferred from the URL or the asset, or derived fromheightand the aspect ratio.height
number
Height in pixels. Appended as
hto the URL and used by the loader for aspect ratio calculations. Optional from 13.5.0: when omitted, it's inferred from the URL or the asset, or derived fromwidthand the aspect ratio.queryParams
Record<string, string | number>
Additional image transformation parameters merged into the image URL, for example
{ blur: 50 }. Sizing parameters (w,h,rect) are ignored. For image objects and asset IDs,fit,crop, andfp-xwithfp-yare passed to the URL builder before it computes the crop. Requires 13.5.0 or later.quality
number
Image quality (0-100). Passed through as
qto the Sanity CDN. Next.js warns when the value isn't listed inimages.qualitiesin your Next.js config.loader
never
Not supported. If you pass a custom loader, the component throws a
TypeError:The `loader` prop is not supported on `Image` components. Use `next/image` directly to use a custom loader.
All other next/image props, such as alt, preload, fill, sizes, placeholder, className, and ref, are passed through to the underlying next/image component.
Use the image loader with the next/image component
If you need more control over the next/image component but still want Sanity CDN URL handling, use the exported imageLoader directly. next/image is a Client Component, and Server Components can't pass functions such as loader to it, so put the component in a file that starts with 'use client':
'use client'
import NextImage from 'next/image'
import { imageLoader } from 'next-sanity/image'
export function CustomImage({ src }: { src: string }) {
return (
<NextImage
loader={imageLoader}
src={src}
alt="Product photo"
width={800}
height={600}
sizes="(max-width: 768px) 100vw, 800px"
/>
)
}Pass a URL with both dimensions set, for example urlFor(image).width(800).height(600).url(). Unlike the Image component, imageLoader doesn't add the width and height props to the URL, so the loader needs w and h on the URL to recalculate h and keep the aspect ratio at each srcSet width.
Without 'use client', the build fails with Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server". In versions before 13.5.0, imageLoader was exported from a client module, so passing it from a Server Component worked.
Art direction with getImageProps
From 13.5.0, imageLoader is a plain function you can call from Server Components. Combine it with getImageProps from next/image to serve different crops at different screen sizes in a <picture> element:
import { getImageProps } from 'next/image'
import { imageLoader } from 'next-sanity/image'
function withSize(url: string, width: number, height: number) {
const src = new URL(url)
src.searchParams.set('w', String(width))
src.searchParams.set('h', String(height))
return src.toString()
}
export function HeroImage({ url, alt }: { url: string; alt: string }) {
const common = { alt, loader: imageLoader }
const {
props: { srcSet: desktop },
} = getImageProps({ ...common, src: withSize(url, 1600, 900), width: 1600, height: 900 })
const {
props: { srcSet: mobile, ...rest },
} = getImageProps({ ...common, src: withSize(url, 800, 800), width: 800, height: 800 })
return (
<picture>
<source media="(min-width: 1000px)" srcSet={desktop} />
<source media="(min-width: 500px)" srcSet={mobile} />
<img {...rest} style={{ width: '100%', height: 'auto' }} />
</picture>
)
}getImageProps doesn't add the dimensions to the URL the way Image does, so include w and h in each src.
Pass a URL instead of an image object
src also accepts a Sanity CDN URL string, such as an asset->url value or a URL you build with @sanity/image-url. Use a URL when you need builder methods that queryParams doesn't cover, or when you're on a version earlier than 13.5.0. See Presenting images for full builder setup:
import { createImageUrlBuilder, type SanityImageSource } from '@sanity/image-url'
import { client } from './client'
const builder = createImageUrlBuilder(client)
export function urlFor(source: SanityImageSource) {
return builder.image(source)
}The URL builder respects crop and hotspot settings when you pass the full image object, not only the asset reference. The hotspot is applied only when you set both width() and height() on the builder. Image infers its width and height from the w and h parameters on the URL, so you don't have to repeat them:
<Image
src={urlFor(post.mainImage).width(1200).height(675).url()}
alt={post.title ?? ''}
preload
/>Relationship to the @sanity/image-url package
next-sanity/image uses @sanity/image-url internally:
@sanity/image-urlbuilds a Sanity CDN URL string from image data. It handles crop, hotspot, and transformation parameters.next-sanity/imagebuilds that URL for you when you pass an image object, or takes a URL you built, and integrates it withnext/imageso you get automaticsrcSetgeneration, format negotiation, and responsive loading from the Sanity CDN.
Use @sanity/image-url on its own with a plain <img> tag or another framework's image component. In Next.js, the Image component from next-sanity/image gives you both: Sanity CDN transformations with next/image optimizations.
Related resources
- Presenting images: configuring
@sanity/image-url, crop and hotspot, responsive images, and performance tips. - Image transformations: full reference for Sanity CDN URL parameters (
w,h,fit,auto,q, and more). - Image metadata: LQIP placeholders, dimensions, palette, and other metadata available for Sanity images.
- Image schema type: schema configuration for image fields, including crop and hotspot options.