Sanity Image Pipeline

Transform, optimize, and deliver images globally through Sanity's powerful on-demand image pipeline with automatic CDN distribution.

Why the Image Pipeline Matters

Images typically account for 50-80% of total page weight, directly impacting Core Web Vitals, SEO rankings, and user engagement. Sanity's image pipeline eliminates the need for external image services or preprocessing by providing a complete solution for image transformation, optimization, and global delivery--all through simple URL parameters.

Unlike traditional CMS platforms that require pre-generating multiple image sizes or integrating third-party CDNs, Sanity handles everything on-demand. Upload high-resolution assets once, and the pipeline automatically serves appropriately sized, optimized versions based on each visitor's device and browser capabilities.

The business value extends beyond technical convenience. By centralizing image management in Sanity, development teams eliminate the overhead of maintaining separate image processing infrastructure. Content editors gain autonomy through intuitive hotspot and crop controls, ensuring images always look their best without developer intervention. The global CDN ensures fast delivery to audiences worldwide, with cached transformations eliminating repeated processing overhead. This combination of reduced maintenance, consistent quality, and optimized performance makes the image pipeline a foundational component of any modern Sanity-powered digital experience.

This guide is part of our Platform Docs series, which covers everything from schema design to GROQ queries for comprehensive content fetching. If you're just getting started with Sanity, our getting started guide provides the foundation you need before diving into image handling.

Image Pipeline Capabilities

Everything you need for modern image delivery

On-Demand Transformations

Resize, crop, and format images dynamically using simple URL parameters. No preprocessing required.

Automatic Format Optimization

Serve WebP or AVIF automatically based on browser support, reducing file sizes by 30-50%.

Smart Cropping with Hotspot

Editors define focal points that are automatically respected when images are cropped to different aspect ratios.

Global CDN Distribution

Images cached at edge locations worldwide for minimal latency regardless of visitor location.

Responsive Image Support

Generate srcset-compatible URLs for optimal image delivery across all device sizes and resolutions.

Single Asset, Multiple Uses

One uploaded asset can be reused with different crops, formats, and sizes across your entire site.

Understanding Image Assets in Sanity

Before diving into transformations, it's essential to understand how Sanity represents and manages images at a fundamental level. This model enables the flexibility and efficiency that makes the image pipeline so powerful.

The Image Type and Asset Model

In Sanity, images follow a two-part model:

The Image Field - Used in documents or embedded in Portable Text, this contains:

  • A reference to the underlying asset
  • Optional fields like caption, alt text, and credits
  • Crop and hotspot settings defined by editors
  • Custom metadata specific to that usage

The Asset Document - Contains the actual image data:

  • Original file metadata (dimensions, format, size)
  • The actual image file in the CDN
  • Asset-level metadata (EXIF, color space, etc.)

This separation means one asset can be referenced by multiple images with different crops, captions, and hotspots. Upload a product photo once, then use it across your site with different aspect ratios for hero banners, thumbnails, and galleries.

Image URL Structure

Every Sanity image URL contains all the information needed to locate and transform the asset. The URL follows a predictable structure that makes it easy to understand and manipulate programmatically.

Sanity Image URL Anatomy Diagram

Diagram showing the components of a Sanity image URL with labeled sections for CDN host, project ID, dataset, asset ID, dimensions, and format.

Image URL Anatomy
https://cdn.sanity.io/images/zp7mbokg/production/G3i4emG6B8JnTmGoN0UjgAp8-300x450.jpg
 │ │ │ │ │ │ └── File format (jpg)
 │ │ │ │ └─── Original height (450px)
 │ │ │ └─── Asset ID + Original dimensions
 │ │ └── Dataset name (production)
 │ └── Project ID (zp7mbokg)
 └── CDN base URL (https://cdn.sanity.io/images)

Image Transformations

The transformation system is the heart of Sanity's image pipeline. Every transformation is specified through URL query parameters, making it trivial to generate optimized images on the fly. The pipeline processes transformations in order: crop → resize → effects.

Basic Resize Operations

The w and h parameters control image dimensions. You can specify either width, height, or both to achieve the desired output size. The fit parameter determines how the pipeline handles aspect ratio preservation when both dimensions are specified.

Width-only examples:

  • ?w=800 - Scale to 800px width, maintain aspect ratio
  • ?w=400&fit=max - Scale to 400px max, never upscale smaller images

Height-only examples:

  • ?h=600 - Scale to 600px height, maintain aspect ratio
  • ?h=200 - Create thumbnail from height

Both dimensions examples:

  • ?w=800&h=600&fit=clip - Fit within 800x600, no cropping
  • ?w=800&h=600&fit=crop - Fill 800x600 by cropping excess
  • ?w=400&h=400&fit=crop - Create square crop from center

Crop Operations

The rect parameter allows precise pixel-based cropping: ?rect=left,top,width,height. For example, ?rect=50,50,200,200 crops a 200x200 square starting 50 pixels from the left and top edges.

Effect Operations

Beyond resizing, Sanity supports effects like blur (?blur=100), sharpen (?sharpen=20), grayscale (?sat=-100), and color inversion (?invert=true). These can be combined with resize operations for creative effects like progressive placeholders.

Device Pixel Ratio

For high-DPI displays, use ?dpr=2 or ?dpr=3 to generate images at 2x or 3x resolution. Combined with responsive image patterns, this ensures crisp visuals on retina displays without manual calculations.

As documented in Sanity's image transformation reference, all parameters can be combined to achieve complex transformations in a single request.

Core Transformation Parameters
ParameterTypeDescriptionExample
wintegerWidth in pixels, scales image to this width?w=800
hintegerHeight in pixels, scales image to this height?h=600
fitstringHow to handle aspect ratio (clip, crop, fill, etc.)?fit=crop
autostringAuto-optimize formats with ?auto=format?auto=format
fmstringForce format (jpg, png, webp, pjpg)?fm=webp
qintegerQuality 0-100, defaults vary by format?q=85
rectcoordsCrop: left,top,width,height in pixels?rect=10,20,100,100
blurintegerBlur 1-2000?blur=50
sharpenintegerSharpen 0-100?sharpen=20
dprnumberDevice pixel ratio 1-3?dpr=2

Fit Mode Reference

The fit parameter controls how images are handled when you specify dimensions:

Fit ModeBehavior
clip (default)Resize to fit within bounds without cropping
cropFill dimensions by cropping when both w and h specified
fillLike clip, fill excess with bg color
fillmaxFill without upscaling, fill excess with bg color
maxFit within bounds without upscaling
scaleStretch to exact dimensions (ignores aspect ratio)
minResize to match aspect without exceeding original

Fit Mode Examples

Visual comparison of each fit mode applied to the same source image at 400x400 output dimensions. Notice how clip preserves the full image within bounds, crop fills the square by trimming edges, and max prevents upscaling for smaller source images.

When choosing a fit mode, consider your design requirements. Use crop for hero images and cards where you need consistent aspect ratios. Use clip or max for images where preserving the entire original is important. For thumbnails of user-uploaded content, fillmax ensures images are never stretched beyond their original quality.

For detailed specifications on each fit mode, refer to Sanity's image transformation documentation.

URL Transformation Examples
1// Common transformation examples2 3// 1. Resize to specific dimensions (maintains aspect)4https://cdn.sanity.io/images/PROJECT/DATASET/image-800x600.jpg?w=400&h=3005 6// 2. Crop to fill specific aspect ratio (focus on center)7https://cdn.sanity.io/images/PROJECT/DATASET/image-800x600.jpg?w=400&h=400&fit=crop8 9// 3. Auto-format for optimal browser support10https://cdn.sanity.io/images/PROJECT/DATASET/image.jpg?auto=format11 12// 4. Specific format with quality13https://cdn.sanity.io/images/PROJECT/DATASET/image.jpg?fm=webp&q=8014 15// 5. Crop to specific region then resize16https://cdn.sanity.io/images/PROJECT/DATASET/image.jpg?rect=50,50,200,200&w=15017 18// 6. High-DPI version for retina displays19https://cdn.sanity.io/images/PROJECT/DATASET/image.jpg?w=800&dpr=220 21// 7. Progressive blur effect22https://cdn.sanity.io/images/PROJECT/DATASET/image.jpg?blur=100&w=5023 24// 8. Prevent upscaling (useful for thumbnails)25https://cdn.sanity.io/images/PROJECT/DATASET/image.jpg?w=400&fit=max

Using the @sanity/image-url Builder

For JavaScript/TypeScript projects, the @sanity/image-url package provides a chainable API that generates image URLs while automatically respecting crop and hotspot settings. This approach is more readable and maintainable than manually constructing URLs.

Installation and Setup

Install the package via npm or yarn, then configure the builder with your Sanity client. The builder requires a configured client instance to access your project ID and dataset.

npm install @sanity/image-url

Once installed, create a reusable urlFor function that wraps the builder. This function becomes the central point for all image URL generation in your application, ensuring consistent transformation patterns across your codebase.

The builder automatically applies editor-defined crop settings first, then uses hotspot data for additional cropping when needed. This means your frontend code automatically respects the choices content editors make in Sanity Studio--no additional logic required. For customizing the Studio experience with image-specific tools, see our guide on Sanity Studio customization.

Setting Up the Image URL Builder
1import { createImageUrlBuilder } from '@sanity/image-url'2import type { SanityImageSource } from '@sanity/image-url'3import { client } from './client'4 5// Create the URL builder with your Sanity client6const builder = createImageUrlBuilder(client)7 8// Export a reusable function9function urlFor(source: SanityImageSource) {10 return builder.image(source)11}12 13// Usage examples:14const imageUrl = urlFor(sanityImageObject)15 .width(800)16 .height(600)17 .fit('crop')18 .blur(50)19 .auto('format')20 .url()21 22// The builder automatically handles:23// - Editor-defined crop settings24// - Hotspot focal points25// - All URL encoding

Crop and Hotspot System

Sanity's crop and hotspot feature gives content editors precise control over how images are cropped at different sizes--without requiring developer intervention for every new image.

How It Works

Crop defines a fixed region of the image that should always be used. When an editor sets a crop, only that portion of the image can be displayed. This is useful when you know exactly which part of an image matters.

Hotspot defines a focal point that should be preserved when the image needs additional cropping. This is ideal for images where important content might otherwise be cut off at different aspect ratios--like product photos where the product should always remain visible.

Editor Experience

In Sanity Studio, editors can:

  1. Define a crop region by dragging to select the desired area
  2. Set a hotspot by clicking to mark the focal point
  3. Preview how the image looks at various aspect ratios

The system stores these as fractions (0.0 to 1.0) of the original image dimensions, making them resolution-independent.

Developer Integration

When you pass an image object to the URL builder, it automatically applies crop first, then uses hotspot coordinates to determine the focus area when additional cropping is required. The builder handles all the math--converting fractional coordinates to pixel values based on the requested output size.

This seamless integration means your responsive images always respect editor intent. A hero image with a face in the top-right will keep that face visible whether it's displayed on a desktop wide banner or a mobile device with a 4:3 crop.

For implementation details, see our guide on Sanity Schema Design to learn how to add hotspot and crop fields to your image types.

Image with Crop and Hotspot Data
1{2 "image": {3 "_type": "image",4 "asset": {5 "_ref": "image-G3i4emG6B8JnTmGoN0UjgAp8-300x450-jpg",6 "_type": "reference"7 },8 // Crop removes bottom 44% of image9 "crop": {10 "bottom": 0.44,11 "left": 0,12 "right": 0,13 "top": 014 },15 // Hotspot focuses on area 43% from left, 26% from top16 // This area (44% width x 65% height) should be preserved17 "hotspot": {18 "height": 0.44,19 "width": 0.65,20 "x": 0.43,21 "y": 0.2622 }23 }24}25 26// The URL builder automatically applies crop first,27// then uses hotspot to determine focus when cropping to specific sizes

Asset CDN and Global Distribution

Sanity's asset CDN is a globally-distributed content delivery network that caches images at edge locations worldwide. This architecture provides significant performance benefits without any configuration.

How the CDN Works

  1. First Request: Image is processed at the origin and cached at the edge location closest to the visitor
  2. Subsequent Requests: Identical URLs are served directly from the nearest edge cache
  3. Cache Updates: When assets are replaced, caches are invalidated automatically

CDN Edge Locations

Diagram showing Sanity CDN edge locations across North America, Europe, Asia-Pacific, and other regions, with sample latency numbers for each location.

Performance Benefits

  • Reduced Latency: Images served from nearby edge locations, not distant origin servers
  • Parallel Downloads: Browser can download images from multiple CDN domains
  • Automatic Optimization: Each unique transformation is cached after first request

Cache Optimization Strategy

To maximize cache efficiency:

  • Use consistent transformation patterns across your site
  • Avoid ad-hoc size requests--pre-define common sizes
  • The more consistent your URLs, the better your cache hit rate

By establishing 3-5 standard image sizes that work across your responsive breakpoints, you ensure that transformed images are reused across multiple pages. A 400px-wide image for mobile tablets, for instance, gets cached after the first page loads and serves instantly for all subsequent visitors.

For more on connecting Sanity to frontend frameworks, see our Next.js integration guide.

Performance Optimization

Optimizing image delivery is critical for Core Web Vitals, SEO, and user experience. Sanity's pipeline provides everything you need to deliver fast-loading images at scale.

Essential Optimization Techniques

Automatic Format Selection The auto=format parameter is your most important optimization. It automatically serves WebP to browsers that support it, or falls back to JPEG/PNG for older browsers. WebP typically reduces file sizes by 30-50% compared to JPEG at equivalent quality, with no perceptible difference in visual quality.

Quality Tuning The q parameter controls compression quality (0-100). Values of 80-85 typically provide excellent quality with minimal file size. Test with your specific images to find the sweet spot. For photographic content, 80 is often indistinguishable from original. For graphics with text, you may prefer 85-90.

Smart Resizing Always request images at or below their displayed size. A 1920px hero image displayed at 100vw on desktop should still be requested at 1920px width--but thumbnails in a grid should request smaller dimensions, not rely on CSS to scale down a large image.

Preventing Upscaling Use fit=max or fit=fillmax for thumbnails or when displaying user-generated content of unknown sizes. This ensures small images aren't stretched, which would create blurry, unprofessional results.

For teams building high-performance web applications, combining Sanity's image pipeline with comprehensive web development services ensures your entire media strategy is optimized for speed and user experience. As outlined in Sanity's image presentation guide, combining these techniques provides optimal performance without sacrificing visual quality.

Implementing Responsive Images
1import { urlFor } from '@/lib/sanity-image-url'2 3function ResponsiveImage({ image, alt }: { image: any; alt: string }) {4 // Generate srcset for responsive delivery5 const srcSet = [6 urlFor(image).width(400).url(),7 urlFor(image).width(800).url(),8 urlFor(image).width(1200).url(),9 urlFor(image).width(1600).url(),10 ].join(', ')11 12 return (13 <img14 src={urlFor(image).width(800).url()}15 srcSet={srcSet}16 sizes="(max-width: 640px) 400px,17 (max-width: 1024px) 800px,18 (max-width: 1280px) 1200px,19 1600px"20 alt={alt}21 loading="lazy"22 decoding="async"23 />24 )25}26 27// For hero images above the fold, use loading="eager" and priority28function HeroImage({ image }: { image: any }) {29 return (30 <img31 src={urlFor(image).width(1920).auto('format').url()}32 alt="Hero image"33 loading="eager"34 fetchPriority="high"35 className="w-full h-auto"36 />37 )38}
Performance Best Practices

Always Use auto=format

Automatically serve WebP or AVIF based on browser support, reducing file sizes by 30-50%.

Predefine Common Sizes

Use 3-5 standard sizes across your site for better cache hit rates and consistent results.

Implement Responsive Images

Use srcset to let browsers select the optimal size based on viewport and device.

Avoid Upscaling

Use fit=max or fit=fillmax to prevent small images from being stretched.

Prioritize Above-Fold Images

Use loading=eager and fetchPriority=high for hero images and LCP elements.

Lazy Load Below-Fold

Apply loading=lazy to images outside the initial viewport.

Frequently Asked Questions

Ready to Optimize Your Image Pipeline?

Sanity's image pipeline eliminates the need for external image services while delivering exceptional performance globally.