Use Sanity with Astro

Images and Portable Text in Astro

Render Sanity images with SanityImage and rich text with Portable Text in your Astro components.

Rendering images

Sanity’s asset pipeline serves images from a global CDN with on-demand transforms, automatic format optimization, and metadata like dimensions, color palettes, and blur hashes. In @sanity/astro 4.1.0 and later, <SanityImage> renders Sanity images through Astro’s astro:assets pipeline and lets the Sanity CDN do the transforms. It needs Astro 5 or later.

Register the image service

Set sanityImageService() as the image service in your Astro config:

import sanity, { sanityImageService } from '@sanity/astro'
import { defineConfig } from 'astro/config'

export default defineConfig({
  image: { service: sanityImageService() },
  integrations: [sanity({ projectId: '', dataset: 'production' })],
})

sanityImageService() answers transforms for Sanity CDN URLs with CDN URLs, so the CDN resizes, crops, and serves AVIF or WebP at the edge and nothing is processed at build time. Other images still go through Astro’s default sharp service. Astro’s own <Image>, <Picture>, and getImage() also get CDN URLs when you pass them a Sanity image URL. If you serve images from a custom CDN domain, add it with sanityImageService({ hostnames: ['cdn.sanity.io', 'images.example.com'] }).

Render an image field

Query the whole image field, not only asset->url, so the component gets the crop and hotspot. Dereference the asset with its url and metadata.lqip to get a blur placeholder. Then pass the field to <SanityImage> as src:

---
import { isImageWithAsset, SanityImage } from '@sanity/astro/image'
import { sanityClient } from 'sanity:client'

const post = await sanityClient.fetch(
  `*[_type == "post" && slug.current == $slug][0]{
    title,
    mainImage{ crop, hotspot, alt, asset->{ url, metadata { lqip } } }
  }`,
  { slug: Astro.params.slug },
)
---

{isImageWithAsset(post.mainImage) && (
  <SanityImage
    src={post.mainImage}
    alt={post.mainImage.alt ?? ''}
    width={1200}
    height={630}
    placeholder="blur"
  />
)}

An image field has no asset until an editor uploads one, so check it with isImageWithAsset before you render it.

  • The studio crop is applied. When width and height give a different aspect ratio, the CDN crops around the hotspot. With fit="cover" (Astro 5.10 and later) or object-fit: cover, object-position defaults to the hotspot.
  • If you leave out width or height, the missing dimension is inferred from the crop, the other dimension, or the asset filename, without a request to measure the image.
  • placeholder="blur" uses asset.metadata.lqip when the query includes it.
  • src also accepts asset documents and references, asset IDs, stega-encoded values from Visual Editing, and Sanity CDN URLs. The project ID and dataset come from the integration config.
  • queryParams adds image transformation parameters, for example queryParams={{ sat: -100 }}. Every other <Image> prop also works, including widths, densities, sizes, quality, and format.

Art direction with <Picture> and getImage()

getSanityImageProps() returns the src, width, height, and style that <SanityImage> passes on. Use it with <Picture> or getImage(). For art direction, build one image per breakpoint:

---
import { getImage } from 'astro:assets'
import { getSanityImageProps } from '@sanity/astro/image'

const { image } = Astro.props
const wide = await getImage({
  ...getSanityImageProps(image, { width: 1600, height: 900 }),
  widths: [800, 1600],
})
const tall = await getImage(getSanityImageProps(image, { width: 800, height: 1000 }))
---

<picture>
  <source media="(min-width: 768px)" srcset={wide.srcSet.attribute} />
  <img src={tall.src} {...tall.attributes} alt="" />
</picture>

Type image props with TypeGen

To type a component that accepts an image from any of your queries, use InferImageValue on your TypeGen query results, or InferStrictImageValue for only the values that have an asset. Both accept stega-encoded results:

import type { InferImageValue } from '@sanity/astro/image'
import type { SanityQueries } from '@sanity/client'

type ImageValue = InferImageValue<SanityQueries[keyof SanityQueries]>

Build image URLs yourself

On Astro versions before 5, or when you need a URL rather than an image element, build URLs with @sanity/image-url:

import type { SanityImageSource } from '@sanity/astro/image'
import { createImageUrlBuilder } from '@sanity/image-url'
import { sanityClient } from 'sanity:client'

const builder = createImageUrlBuilder(sanityClient)

export function urlFor(source: SanityImageSource) {
  return builder.image(source)
}
---
import { urlFor } from '../lib/image'

const { image, alt } = Astro.props
---

<img src={urlFor(image).width(800).auto('format').url()} alt={alt} width="800" loading="lazy" />

The auto('format') option serves modern formats like AVIF or WebP based on browser support, and falls back to the original format for others.

Rendering Portable Text

Sanity stores rich text as Portable Text, a JSON-based format. The Sanity-maintained @portabletext/astro library handles rendering in Astro.

Basic rendering

---
import { PortableText } from '@portabletext/astro'
import type { PortableTextProps } from '@portabletext/astro/types'

interface Props {
  value: PortableTextProps['value']
}

const { value } = Astro.props
---

<PortableText value={value} />

Custom block types and annotations

If your schema includes custom block types (like code blocks, images, or YouTube embeds), map them to Astro components:

---
import { PortableText as PortableTextInternal } from '@portabletext/astro'
import type { PortableTextProps } from '@portabletext/astro/types'
import CodeBlock from './CodeBlock.astro'
import PortableTextImage from './PortableTextImage.astro'
import YouTubeEmbed from './YouTubeEmbed.astro'
import InternalLink from './InternalLink.astro'

interface Props {
  value: PortableTextProps['value']
}

const { value } = Astro.props

const components = {
  type: {
    code: CodeBlock,
    image: PortableTextImage,
    youtube: YouTubeEmbed,
  },
  mark: {
    internalLink: InternalLink,
  },
}
---

<PortableTextInternal value={value} components={components} />

Each component receives the block data as props. For the full API, see the @portabletext/astro README.

Example: image block

Wrap <SanityImage> so it reads the image from the node prop that Portable Text passes to each block component:

---
import { isImageWithAsset, SanityImage } from '@sanity/astro/image'

// `node` is the image block from Portable Text
const { node } = Astro.props
---

{isImageWithAsset(node) && (
  <SanityImage src={node} alt={node.alt ?? ''} width={800} placeholder="blur" />
)}

Example: code block component

---
interface Props {
  node: {
    code: string
    language?: string
    filename?: string
  }
}

const { node } = Astro.props
---

{node.filename && <div class="code-filename">{node.filename}</div>}
<pre><code class={`language-${node.language || 'text'}`}>{node.code}</code></pre>

Example: internal link annotation

Annotation components receive the annotated text as node, and the annotation’s data is on node.markDef. This example expects your query to resolve the linked document’s slug onto the annotation, for example with markDefs[]{ ..., _type == "internalLink" => { "slug": @.reference->slug } } inside the body[] projection.

---
import type { MarkProps } from '@portabletext/astro/types'

type Props = MarkProps<{ slug?: { current: string } }>

const { node } = Astro.props
const href = node.markDef.slug ? `/${node.markDef.slug.current}` : '#'
---

<a href={href}><slot /></a>

Querying images and rich text together

A typical query for a content page includes both image references and Portable Text body content:

*[_type == "post" && slug.current == $slug][0]{
  title,
  "mainImage": mainImage{
    asset->,
    crop,
    hotspot,
    alt,
    caption
  },
  body[]{
    ...,
    _type == "image" => {
      asset->,
      alt,
      caption
    },
    _type == "block" => {
      markDefs[]{
        ...,
        _type == "internalLink" => { "slug": @.reference->slug }
      }
    }
  },
  "author": author->{
    name,
    "imageUrl": image.asset->url
  }
}

The asset-> dereference on images gives you the full asset document, including the URL, dimensions, and the LQIP that <SanityImage> uses for blur placeholders. Include crop and hotspot so the studio crop applies. The body[]{ ... } projection keeps every field of inline images, including their crop and hotspot, and adds their asset data. Keep asset in every image projection, either as the reference or dereferenced: isImageWithAsset returns false for an image without an asset reference, ID, or URL, so <SanityImage> won’t render. See Render an image field.

Was this page helpful?

Sanity logosanity.ioAll Systems Operational© Sanity 2026
Change site theme