Use Sanity with Next.js

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.

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.

Render 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.

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 width and height you 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:

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:

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 w and h parameters in the image URL, for example from an @sanity/image-url builder.
  • The rect crop 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:

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="" />
  • queryParams ignores the sizing parameters w, h, and rect. The image size comes from the width and height props, the URL, and the crop and hotspot.
  • For image objects and asset IDs, fit, the crop mode (crop), and a focal point (fp-x with fp-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 in T, which can be a query result type, a union of query results, or a schema type. It accepts both stega-branded results from sanityFetch and clean results.
  • InferStrictImageValue<T>: the same, limited to images that have an asset.
  • isImageWithAsset: narrows an image value to one that has an asset.

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 remotePatterns configuration is needed in next.config.js for Sanity images.
  • Format negotiation (WebP, AVIF) happens at the CDN level through the auto=format parameter, based on the browser's Accept header.
  • Your Next.js server doesn't process the images, reducing its CPU and memory load.
  • The loader automatically maintains aspect ratio across srcSet breakpoints by recalculating the h parameter proportionally for each width.
  • The loader sets sensible defaults for the fit parameter: fit=max when only width is specified (prevents upscaling), fit=min when 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=format so the CDN returns the best format the browser supports (WebP, AVIF). See Image transformations for the full list of URL parameters.
  • Sets fit=max when only width is specified, or fit=min when both width and height are present. If the URL already contains a fit parameter, the loader respects it.
  • Recalculates h proportionally when both w and h are present, preserving the original aspect ratio at each breakpoint.
  • Sets w to the width that next/image requests.
  • Passes the quality prop through as the q URL 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->url or an @sanity/image-url builder.

    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 src isn't a valid absolute URL, the component throws a TypeError: 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 dataset to build the URL when src is 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 w to 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 from height and the aspect ratio.

  • height

    number

    Height in pixels. Appended as h to 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 from width and 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, and fp-x with fp-y are 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 q to the Sanity CDN. Next.js warns when the value isn't listed in images.qualities in 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':

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:

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:

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-url builds a Sanity CDN URL string from image data. It handles crop, hotspot, and transformation parameters.
  • next-sanity/image builds that URL for you when you pass an image object, or takes a URL you built, and integrates it with next/image so you get automatic srcSet generation, 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.

Was this page helpful?