Use Sanity with Astro

Images and Portable Text in Astro

Render Sanity images with CDN transforms 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. Use @sanity/image-url to generate URLs with the transforms you need.

Create an image URL builder

Use it in components

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 community-maintained astro-portabletext library handles rendering in Astro.

Basic rendering

Custom block types and annotations

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

Each component receives the block data as props. For the full API, see the astro-portabletext documentation.

Using Astro's Image component

Astro's built-in <Image> component is designed for local assets and third-party image URLs that are not part of the Sanity pipeline. For images stored in Sanity, use @sanity/image-url instead: it handles format negotiation (AVIF/WebP), resizing, and cropping at the CDN level, with no build-time processing required. If you do use <Image> with Sanity CDN URLs, add the Sanity CDN to your allowed image domains:

Note that passing a Sanity CDN URL to Astro's <Image> component results in double-processing: Sanity's CDN applies its transforms first, then Astro's Sharp pipeline processes the result again at build time. This wastes build time and can degrade image quality.

Example: code block component

Example: internal link annotation

Querying images and rich text together

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

The asset-> dereference on images gives you the full asset document, including dimensions and metadata. The body[]{ ... } projection with the conditional image expansion ensures inline images in Portable Text also include their asset data.

Was this page helpful?