Back to blog
Apr 16, 2025
3 min read

Enable image optimization in Astro

A quick guide to setting up Astro, exploring project structure, and using layouts—plus handy resources to boost your workflow.

To enable image optimization in Astro, you can use Astro’s built-in tools and integrations designed for efficient handling of images. Here’s how you can set it up:


1. Use the astro:assets Module

Astro v3.0 and later uses the astro:assets module for image optimization. This module replaces the deprecated @astrojs/image integration.

Steps:

  1. Import the “ component from astro:assets.
  2. Use the component in your Astro files with properties like src, width, height, and format.

Example:

import { Image } from 'astro:assets';


This automatically optimizes the image, converts it to WebP (if supported), and ensures lazy loading[1][4].


2. Configure Image Optimization Settings

You can customize optimization settings in your astro.config.mjs file.

Example configuration:

import { defineConfig } from 'astro/config';

export default defineConfig({
  image: {
    service: 'sharp', // Specify the image processing library (e.g., Sharp or Squoosh)
    serviceEntryPoint: '@astrojs/image/sharp',
    defaultFormat: 'webp', // Default image format
    cacheDir: './.cache/image', // Cache directory for optimized images
    logLevel: 'info', // Logging level
  },
});

This setup ensures efficient processing and caching of optimized images[4].


3. Programmatic Optimization Using getImage()

For dynamic or programmatic optimization, use the getImage() function.

Example:

import { getImage } from '@astrojs/image';

const optimizedImage = await getImage({
  src: '/path/to/image.jpg',
  width: 800,
  height: 600,
  format: 'webp',
  quality: 80,
});

This function generates optimized images dynamically, which can be used in APIs or application logic[4].


4. Responsive Images with Component

For serving different formats or sizes based on device capabilities, use the “ component.

Example:

import { Picture } from 'astro:assets';

The browser selects the best-supported format automatically[4].


5. Integrate Third-Party Services

Astro supports integrations with services like Cloudinary or Imgix for advanced optimization and CDN delivery.

Example with Cloudinary:

import { defineConfig } from 'astro/config';
import cloudinary from '@astrojs/cloudinary';

export default defineConfig({
  integrations: [
    cloudinary({
      cloudName: 'your-cloud-name',
      apiKey: 'your-api-key',
      apiSecret: 'your-api-secret',
    }),
  ],
});

You can then use “ with Cloudinary-specific properties to serve optimized images globally[4].


By leveraging these tools, you can ensure that your Astro project delivers fast-loading, optimized images across all devices while maintaining high performance and user experience.