🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Performance••By Komal Nakrani

Astro Image Service: Sharp, Passthrough and Custom

How the Astro image service works: Sharp by default, encoder tuning, the passthrough service for hosts without Sharp, and custom local or CDN services.

#Astro#Astro Image Service#Images#Sharp#Performance

An Astro image service is the module that turns an <Image />, <Picture /> or getImage() call into an optimised file and a URL. By default Astro uses a Sharp-based service that resizes and re-encodes images to WebP, AVIF, PNG or JPEG; you can tune it, swap it for the no-op passthrough service, or write your own service that hands transformations to an image CDN.

This explainer covers how the pipeline is wired in Astro 7, how to configure each option, and how to decide which service fits your host.

Key Takeaways

  • The image service is set with image.service in astro.config.mjs; the default is astro/assets/services/sharp.
  • sharpImageService() and passthroughImageService() from astro/config are the quickest way to configure the built-in services.
  • Static builds transform images once at build time; on-demand routes call the service through the /_image endpoint.
  • A local service implements getURL, parseURL and transform; an external service only needs getURL.
  • Use an external service when a CDN already resizes images for you, so your build does no image work at all.

What an image service does

Every time Astro meets an optimisable image, it asks the configured service three questions:

  1. What URL should this image have? (getURL) The service builds a URL that encodes the source and options, such as width, format and quality.
  2. What HTML attributes go on the tag? (getHTMLAttributes, getSrcSet) Width, height, loading, decoding and the srcset for responsive images.
  3. How do I produce the bytes? (transform) Only local services answer this one. They receive the original file as a Uint8Array and return the encoded result.

For prerendered pages, Astro runs transform during astro build and writes the files to dist/_astro/. In astro dev and on routes rendered on demand, images are served through an endpoint, /_image by default, which parses the URL back into options with parseURL and calls transform per request.

That design is why the same <Image /> component can be backed by Sharp on your laptop and by a CDN in production. Our Astro image component guide covers the component side; this article is about what sits underneath.

The default: Sharp

Astro ships a Sharp-based service and lists sharp as an optional dependency, so it is normally installed for you. If your package manager skipped it, for example with strict pnpm settings, the build fails with MissingSharp:

Could not find Sharp. Could not find Sharp. Please install Sharp (sharp) manually into your project or migrate to another image service.

The fix is npm install sharp, or switching to the passthrough service described below. The fix for “Could not find Sharp” tip walks through both.

Tuning Sharp’s encoders

Since Astro 6.1 you can set default encoder options per format. The helper from astro/config gives you typed options:

// astro.config.mjs
import { defineConfig, sharpImageService } from 'astro/config';

export default defineConfig({
  image: {
    service: sharpImageService({
      limitInputPixels: false,
      kernel: 'lanczos3',
      jpeg: { mozjpeg: true },
      webp: { effort: 6, alphaQuality: 80 },
      avif: { effort: 4 },
      png: { compressionLevel: 9 },
    }),
  },
});

The same configuration can be written as an object with entrypoint: 'astro/assets/services/sharp' and a config key. A few notes on the options:

  • limitInputPixels guards against huge source images. Set it to false only if you trust every source file, or to a pixel count that covers your largest legitimate image.
  • kernel controls the resize algorithm. The default suits most photos.
  • Encoder options set defaults; a quality prop on a specific <Image /> still wins for that image.
  • Higher effort values produce smaller files but slow the build, which matters on sites with hundreds of images.

The passthrough service

Some hosts cannot run Sharp, and some projects do not want Astro touching images at all. The passthrough service keeps the <Image /> API, dimensions and srcset attributes but returns the original file unchanged:

// astro.config.mjs
import { defineConfig, passthroughImageService } from 'astro/config';

export default defineConfig({
  image: {
    service: passthroughImageService(),
  },
});

Use it when you deploy server-rendered routes to a runtime without native modules, when images are already optimised before they reach the repository, or when you want the fastest possible builds during development. You lose format conversion and resizing, so pair it with pre-optimised images or a CDN.

Writing an external image service for a CDN

If an image CDN already resizes images on the fly, the cleanest setup is an external service. It only builds URLs; the CDN does the work, so astro build skips image processing entirely.

This example targets Cloudflare’s /cdn-cgi/image/ URL format, which works on zones with image transformations enabled:

// src/image-service.ts
import type { ExternalImageService, ImageTransform } from 'astro';
import { baseService } from 'astro/assets';

function sourcePath(options: ImageTransform) {
  return typeof options.src === 'string' ? options.src : options.src.src;
}

const service: ExternalImageService = {
  validateOptions: baseService.validateOptions,
  getHTMLAttributes: baseService.getHTMLAttributes,
  getSrcSet: baseService.getSrcSet,
  getURL(options, imageConfig) {
    const params = [
      options.width && `width=${options.width}`,
      options.height && `height=${options.height}`,
      `quality=${options.quality ?? imageConfig.service.config.quality ?? 80}`,
      `format=${options.format ?? 'auto'}`,
      options.fit && `fit=${options.fit}`,
    ].filter(Boolean);
    return `/cdn-cgi/image/${params.join(',')}${sourcePath(options)}`;
  },
};

export default service;
// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  image: {
    service: {
      entrypoint: './src/image-service.ts',
      config: { quality: 75 },
    },
  },
});

Borrowing validateOptions, getHTMLAttributes and getSrcSet from baseService keeps Astro’s standard behaviour for attributes and responsive sizes, so only URL generation is custom. Anything you put in config is available as imageConfig.service.config.

Writing a local image service

A local service does the transformation itself. That is the route to take if you want a different image library, a watermark, or a custom format pipeline. You implement parseURL and transform, and reuse the rest from baseService:

// src/watermark-service.ts
import type { LocalImageService } from 'astro';
import { baseService } from 'astro/assets';
import sharp from 'sharp';

const service: LocalImageService = {
  ...baseService,
  async transform(inputBuffer, options) {
    const width = options.width ? Number(options.width) : undefined;
    const format = (options.format ?? 'webp') as 'webp' | 'avif' | 'png' | 'jpeg';

    const mark = Buffer.from(
      '<svg width="220" height="40"><text x="10" y="28" font-size="22" fill="white" opacity="0.7">example.com</text></svg>'
    );

    const data = await sharp(inputBuffer)
      .resize({ width })
      .composite([{ input: mark, gravity: 'southeast' }])
      .toFormat(format, { quality: options.quality ? Number(options.quality) : 80 })
      .toBuffer();

    return { data: new Uint8Array(data), format };
  },
};

export default service;

Register it the same way, with entrypoint: './src/watermark-service.ts'. If your service adds options that change the output, list them in propertiesToHash so Astro does not reuse a cached file generated with different settings.

Choosing an image service

Situation Service
Static site on any host Sharp (default)
Large build times from many images Sharp with lower effort, or an external CDN service
Server routes on a runtime without native modules Passthrough, or an external service
Images already optimised in the repo Passthrough
Image CDN available (Cloudflare, Cloudinary, imgix) External service
Watermarks or custom processing Custom local service

Most static sites, including every Komal theme, work well with the default Sharp service and need no configuration. The Astro styling docs cover where theme images live.

Remote images and SVG

Two related settings sit next to image.service:

  • image.domains and image.remotePatterns decide which remote URLs may be optimised. Anything else is rendered as-is. Our tip on responsive images shows them in use.
  • image.dangerouslyProcessSVG (Astro 6.3+) lets SVG sources go through the transform pipeline. It is off by default because crafted SVGs can be very expensive to rasterise; enable it only for SVGs you control.

The official images guide and the image service API reference document every hook.

FAQ

What image service does Astro use by default?

Astro uses a Sharp-based service, astro/assets/services/sharp. It resizes images and converts them to WebP, AVIF, PNG or JPEG. Sharp is installed as an optional dependency of Astro.

How do I disable image optimisation in Astro?

Set image.service to passthroughImageService() from astro/config. Images keep their dimensions and srcset attributes but are served unchanged, and Sharp is no longer needed.

Can I use Cloudinary or imgix with Astro’s Image component?

Yes. Write an external image service whose getURL builds the CDN’s URL from the width, height, format and quality, or use a community integration for your CDN. The <Image /> component then outputs CDN URLs and the build skips image processing.

What is the difference between a local and an external image service?

A local service transforms images itself through transform and serves them from your build output or the /_image endpoint. An external service only generates URLs that point to another server or CDN, which does the transformation.

Does the image service affect build time?

Yes. With Sharp, every image size and format is generated during astro build, so sites with many images build more slowly. Lower encoder effort, fewer widths or an external CDN service all reduce that cost.