Image Optimization for Astro — A Practical Guide
Images often account for the majority of page weight. A few optimizations can cut load times in half. Here’s how Astro helps and what to do manually.
The Astro Image Component
Astro provides <Image> for automatic optimization:
---
import { Image } from 'astro:assets';
import myImage from '../assets/hero.png';
---
<Image src={myImage} alt="Hero" width={1200} height={630} />
Astro will:
- Convert to WebP/AVIF when supported
- Generate responsive
srcset - Add
widthandheightto prevent CLS - Lazy load by default for below-the-fold images
Remote Images
For images from URLs (CDNs, CMS, etc.), use the same component with a string:
<Image
src="https://example.com/photo.jpg"
alt="Description"
width={800}
height={450}
/>
Configure allowed domains in astro.config.mjs:
export default defineConfig({
image: {
domains: ['example.com', 'cdn.example.com'],
},
});
Responsive Images
Let Astro generate multiple sizes:
<Image
src={myImage}
alt="Responsive"
widths={[400, 800, 1200]}
sizes="(max-width: 768px) 100vw, 50vw"
/>
The sizes attribute tells the browser which width to request at different viewport sizes. Match it to your layout.
Aspect Ratio and Placeholders
Reserve space to prevent layout shift:
<Image
src={myImage}
alt="..."
width={800}
height={450}
aspectRatio={16/9}
/>
For blur placeholders, use a low-quality base64 or LQIP. Some themes (including Hermes Prime) include placeholder support for progressive loading.
When to Use Picture
For art direction—different crops on mobile vs desktop—use <Picture>:
import { Picture } from 'astro:assets';
<Picture
src={myImage}
widths={[400, 800, 1200]}
formats={['avif', 'webp']}
alt="..."
/>
Lazy Loading
Below-the-fold images get loading="lazy" by default. Above-the-fold (hero images) should use loading="eager" or omit the attribute so they load immediately.
Format Priority
Modern browsers support AVIF and WebP. Astro serves them when the format is smaller. Fallback to JPEG/PNG for older browsers. You rarely need to configure this—Astro chooses well.
CDN and Caching
If you use a CDN (Cloudflare, Vercel, etc.), ensure image URLs are cacheable. Astro’s output uses hashed filenames, so long cache times are safe. Set Cache-Control headers for /dist/_astro/* to something like max-age=31536000, immutable.
Checklist
- Use Astro’s Image component for local and remote images
- Always include
width,height, oraspectRatio - Add descriptive
alttext for accessibility - Use
sizesthat match your layout - Lazy load below-the-fold images
- Preload critical above-the-fold images if needed
Images don’t have to slow you down. With Astro and a few habits, you can serve fast, beautiful images without thinking about it.