Astro Image Optimization Guide

Astro's built-in image optimization automatically compresses, resizes, and converts images to modern formats like WebP and AVIF. This guide covers everything you need to know to optimize images in your Astro site.

Why Image Optimization Matters

Images are often the largest assets on a webpage. Optimizing them improves:

  • Page load speed – smaller files load faster
  • Core Web Vitals – better LCP and CLS scores
  • SEO rankings – Google rewards fast sites
  • User experience – less waiting, less data usage

Using the Astro Image Component

Astro provides a built-in <Image /> component that handles optimization automatically:

---
import { Image } from 'astro:assets';
import myImage from '../assets/hero.png';
---

<Image src={myImage} alt="Hero image" />

The component automatically:

  • Converts images to WebP or AVIF
  • Generates responsive srcset attributes
  • Adds width and height to prevent layout shift
  • Lazy loads images by default

Specifying Image Dimensions

You can resize images by specifying width or height:

<Image src={myImage} width={800} alt="Resized image" />

Remote Images

For remote images, you need to authorize the domain in your config:

// astro.config.mjs
export default defineConfig({
  image: {
    domains: ['example.com', 'cdn.example.com'],
  },
});

Then use the component with a URL:

<Image
  src="https://example.com/image.jpg"
  width={600}
  height={400}
  alt="Remote image"
/>

Choosing Image Formats

Astro defaults to WebP, but you can specify a format:

<Image src={myImage} format="avif" alt="AVIF image" />

Format recommendations:

  • WebP – great balance of quality and size, wide browser support
  • AVIF – best compression, but slower to encode
  • PNG – use for images that need transparency
  • JPEG – fallback for older browsers

The Picture Component

For art direction or multiple formats, use the <Picture /> component:

---
import { Picture } from 'astro:assets';
import myImage from '../assets/hero.png';
---

<Picture
  src={myImage}
  formats={['avif', 'webp']}
  alt="Hero with multiple formats"
/>

Best Practices

  • Always include descriptive alt text for accessibility and SEO
  • Use local images when possible for better optimization
  • Set explicit dimensions to prevent Cumulative Layout Shift (CLS)
  • Use loading="eager" for above-the-fold images
  • Consider using a CDN for production deployments

Related Guides

Looking for optimized Astro templates?

Our recommended templates come with image optimization configured out of the box.