Astro
Image and Assets API Reference
Image and Assets API Reference
Astro provides built-in components and helper functions for optimizing and displaying your images. For features and usage examples, see our image guide.
Imports from astro:assets
The following helpers are imported from the virtual assets module:
<Image />
The <Image /> component optimizes and transforms images.
---
// import the Image component and the image
import myImportedImage from '../assets/my-local-image.png';
---
<Image src={myImportedImage} alt="descriptive text" />
Images in the
public/folder - use the image's file path relative to the public folder:--- import { Image } from 'astro:assets'; --- <Image src="/images/my-public-image.png" alt="descriptive text" width="200" height="150" />Remote images - use the image's full URL as the property value:
--- import { Image } from 'astro:assets'; --- <Image src="https://example.com/remote-image.jpg" alt="descriptive text" width="200" height="150" />
alt (required)
Type: string
Use the required alt attribute to provide a string of descriptive alt text for images.
If an image is merely decorative (i.e. doesn't contribute to the understanding of the page), set alt="" so that screen readers and other assistive technologies know to ignore the image.
width and height (required for images in public/)
Type: number | `${number}` | undefined
These properties define the dimensions to use for the image.
When a layout type is set, these are automatically generated based on the image's dimensions and in most cases should not be set manually.
When using images in their original aspect ratio, width and height are optional. These dimensions can be automatically inferred from image files located in src/. For remote images, add the inferSize attribute set to true on the <Image /> or <Picture /> component or use inferRemoteSize() function.
However, both of these properties are required for images stored in your public/ folder as Astro is unable to analyze these files.
densities
Type: (number | `${number}x`)[] | undefined
A list of pixel densities to generate for the image.
The densities attribute is not compatible with having the layout prop or image.layout config set, and will be ignored if set.
If provided, this value will be used to generate a srcset attribute on the <img> tag. Do not provide a value for widths when using this value.
Densities that are equal to widths larger than the original image will be ignored to avoid upscaling the image.
---
---
<Image
src={myImage}
width={myImage.width / 2}
densities={[1.5, 2]}
alt="A description of my image."
/>
<!-- Output -->
<img
src="/_astro/my_image.hash.webp"
srcset="
/_astro/my_image.hash.webp 1.5x
/_astro/my_image.hash.webp 2x
"
alt="A description of my image."
width="800"
height="450"
loading="lazy"
decoding="async"
/>
widths
Type: number[] | undefined
A list of widths to generate for the image.
If provided, this value will be used to generate a srcset attribute on the <img> tag. A sizes property must also be provided.
The widths and sizes attributes will be automatically generated for images using a layout property. Providing these values is generally not needed, but can be used to override any automatically generated values.
Do not provide a value for densities when using this value. Only one of these two values can be used to generate a srcset.
Widths that are larger than the original image will be ignored to avoid upscaling the image.
---
---
<Image src="https://example.com/cat.png" inferSize alt="A cat sleeping in the sun." />
As of Astro 5.17.3, inferSize only fetches dimensions for authorized remote image domains. Remote images outside the allowlist are not fetched.
priority
Type: boolean
Default: false
Allows you to automatically set the loading, decoding, and fetchpriority attributes to their optimal values for above-the-fold images.
---
---
<Image src={myImage} priority alt="A description of my image" />
When priority="true" (or the shorthand syntax priority) is added to the <Image /> or <Picture /> component, it will add the following attributes to instruct the browser to load the image immediately:
loading="eager"
decoding="sync"
fetchpriority="high"
These individual attributes can still be set manually if you need to customize them further.
layout
Type: 'constrained' | 'full-width' | 'fixed' | 'none'
Default: image.layout | 'none'
Determines how the image should resize when its container changes size. Can be used to override the default configured value for image.layout.
---
---
<Image src={myImage} alt="A description of my image." layout='constrained' width={800} height={600} />
When a layout is set, srcset and sizes attributes are automatically generated based on the image's dimensions and the layout type. The previous <Image /> component will generate the following HTML output:
<img
src="/_astro/my_image.hash3.webp"
srcset="/_astro/my_image.hash1.webp 640w,
/_astro/my_image.hash2.webp 750w,
/_astro/my_image.hash3.webp 800w,
/_astro/my_image.hash4.webp 828w,
/_astro/my_image.hash5.webp 1080w,
/_astro/my_image.hash6.webp 1280w,
/_astro/my_image.hash7.webp 1600w"
alt="A description of my image"
sizes="(min-width: 800px) 800px, 100vw"
loading="lazy"
decoding="async"
fetchpriority="auto"
width="800"
height="600"
style="--fit: cover; --pos: center;"
data-astro-image="constrained"
>
layout supports the following values:
constrained- The image will scale down to fit the container, maintaining its aspect ratio, but will not scale up beyond the specifiedwidthandheight, or the image's original dimensions.Use this if you want the image to display at the requested size where possible, but shrink to fit smaller screens. This matches the default behavior for images when using Tailwind. If you're not sure, this is probably the layout you should choose.
full-width- The image will scale to fit the width of the container, maintaining its aspect ratio.Use this for hero images or other images that should take up the full width of the page.
fixed- The image will maintain the requested dimensions and not resize. It will generate asrcsetto support high density displays, but not for different screen sizes.Use this if the image will not resize, for example icons or logos smaller than any screen width, or other images in a fixed-width container.
none- The image will not be responsive. Nosrcsetorsizeswill be automatically generated, and no styles will be applied.This is useful if you have enabled a default layout, but want to disable it for a specific image.
For example, with constrained set as the default layout, you can override any individual image's layout property:
---
---
<Image src={myImage} alt="This will use constrained layout" width={800} height={600} />
<Image src={myImage} alt="This will use full-width layout" layout="full-width" />
<Image src={myImage} alt="This will disable responsive images" layout="none" />
The value for layout also defines the default styles applied to the <img> tag to determine how the image should resize according to its container:
:where([data-astro-image]) {
object-fit: var(--fit);
object-position: var(--pos);
}
:where([data-astro-image='full-width']) {
width: 100%;
}
:where([data-astro-image='constrained']) {
max-width: 100%;
}
fit
Type: 'contain' | 'cover' | 'fill' | 'none' | 'scale-down'
Default: image.objectFit | 'cover'
Defines how a image should be cropped if its aspect ratio is changed.
Values match those of CSS object-fit. Defaults to cover, or the value of image.objectFit if set. Can be used to override the default object-fit styles.
position
Type: string
Default: image.objectPosition | 'center'
Defines the position of the image crop for a image if the aspect ratio is changed.
Values match those of CSS object-position. Defaults to center, or the value of image.objectPosition if set. Can be used to override the default object-position styles.
background
Type: string | undefined
The background color to use when flattening an image to transform it into the requested output format.
By default, Sharp uses a black background when flattening an image. Specifying a different background color is especially useful when transforming images with transparent backgrounds to a format that does not support transparency (e.g. .jpeg):
<Image
src={myImage}
alt="A description of my image"
format="jpeg"
background="#ffffff"
/>
Values are passed directly to the image service. Sharp accepts any value the color-string package can parse.
<Picture />
The <Picture /> component generates an optimized image with multiple formats and/or sizes.
---
---
<Font cssVariable="--font-roboto" />
The <Font /> component accepts the following properties:
cssVariable (required)
Type: CssVariable
Example type: "--font-roboto" | "--font-comic-sans" | ...
The cssVariable registered in your Astro configuration:
---
---
<Font cssVariable="--font-roboto" />
preload
Type: boolean | { weight?: string | number; style?: string; subset?: string }[]
Default: false
Whether to output preload links or not. With the preload directive, the browser will immediately begin downloading all possible font links during page load:
---
---
<Font cssVariable="--font-roboto" preload />
Be very intentional about which fonts you preload. Preloading too many fonts can impact performance, as this can block loading other important resources or may download fonts that are not needed for the current page.
To selectively control which font files are preloaded, you can provide an array of objects describing any combination of font weight, style, or subset to preload:
---
---
<Font
cssVariable="--font-roboto"
preload={[
{ subset: "latin", style: "normal" },
{ weight: "400" },
]}
/>
Variable weight font files will be preloaded if any weight within its range is requested. For example, a font file for font weight 100 900 will be included when 400 is specified in a preload object.
getImage()
Type: (options: UnresolvedImageTransform) => Promise<GetImageResult>
:::caution
getImage() relies on server-only APIs and will throw an error on the client.
If you need the resulting image URL client-side, you can pass the src from a server-rendered getImage() call to the client.
:::
The getImage() function is intended for generating images destined to be used somewhere else than directly in HTML, for example in an API Route. It also allows you to create your own custom <Image /> component.
This takes an options object with the same properties as the Image component (except alt) and returns a GetImageResult object.
The following example generates an AVIF background-image for a <div />:
---
const { width, height } = await inferRemoteSize("https://example.com/cat.png");
getConfiguredImageService()
Type: () => Promise<ImageService>
Retrieves the resolved image service.
imageConfig
Type: AstroConfig["image"]
The configuration options for images set by the user and merged with all defaults.
fontData
Type: Record<CssVariable, Array<FontData>>
An object where each key is a cssVariable and the value is an array describing the associated fonts. Each font is an object containing an array of src available for that font and the following optional properties: weight and style:
const fontPath = fontData["--font-roboto"][0]?.src[0]?.url;
if (fontPath === undefined) {
throw new Error("Cannot find the font path.");
}
const url = experimental_getFontFileURL(fontPath);
const buffer = await fetch(url).then((res) => res.arrayBuffer());
When called on a route rendered on-demand, the request URL needs to be provided:
// ...
};
astro:assets types
The following types are imported from the virtual assets module:
LocalImageProps
Type: ImageSharedProps<T> & { src: ImageMetadata | Promise<{ default: ImageMetadata; }> }
Describes the properties of a local image. This ensures that src matches the shape of an imported image.
src/ with an example usage.
RemoteImageProps
Types:
ImageSharedProps<T> & { src: string; inferSize: true; }ImageSharedProps<T> & { src: string; inferSize?: false | undefined; }
Describes the properties of a remote image. This ensures that when inferSize is not provided or is set to false, both width and height are required.
FontData
Type: { src: Array<{ url: string; format?: string; tech?: string }>; weight?: string; style?: string; subset?: string; }
Describes the font data associated with a given font family.
FontData.src
Type: Array<{ url: string; format?: string; tech?: string }>
An array of objects describing the available font files for a given font family. Each object contains a url and, optionally, the associated format and tech.
FontData.weight
Type: string
Specifies the font weight (e.g. 400, 600).
FontData.style
Type: string
Specifies the font style (e.g. normal, italic).
FontData.subset
Type: string
Specifies the font subset (e.g. latin, cyrillic).
Imports from astro/assets
The following helpers are imported from the regular assets module:
baseService
Type: Omit<LocalImageService, 'transform'>
The built-in local image service which can be extended to create a custom image service.
The following example reuses the baseService to create a new image service:
const newImageService = {
getURL: baseService.getURL,
parseURL: baseService.parseURL,
getHTMLAttributes: baseService.getHTMLAttributes,
async transform(inputBuffer, transformOptions) {...}
}
getConfiguredImageService()
See getConfiguredImageService() from astro:assets.
getImage()
Type: (options: UnresolvedImageTransform, imageConfig: AstroConfig['image']) => Promise<GetImageResult>
A function similar to getImage() from astro:assets with two required arguments: an options object with the same properties as the Image component and a second object for the image configuration.
isLocalService()
Type: (service: ImageService | undefined) => boolean
Checks the type of an image service and returns true when this is a local service.
astro/assets types
The following types are imported from the regular assets module:
LocalImageProps
See LocalImageProps from astro:assets.
RemoteImageProps
See RemoteImageProps from astro:assets.
Imports from astro/assets/utils
The following helpers are imported from the utils directory in the regular assets module and can be used to build an image service:
isRemoteAllowed()
Type: (src: string, { domains, remotePatterns }: { domains: string[], remotePatterns: RemotePattern[] }) => boolean
Determines whether a given remote resource, identified by its source URL, is allowed based on specified domains and remote patterns.
const url = new URL('https://example.com/images/test.jpg');
const domains = ['example.com', 'anotherdomain.com'];
const remotePatterns = [
{
protocol: 'https',
hostname: 'images.example.com',
pathname: '/**', // Allow any path under this hostname
}
];
isRemoteAllowed(url.href, { domains, remotePatterns }); // Output: `true`
matchHostname()
Type: (url: URL, hostname?: string, allowWildcard = false) => boolean
Matches a given URL's hostname against a specified hostname, with optional support for wildcard patterns.
const url = new URL('https://sub.example.com/path/to/resource');
matchHostname(url, 'example.com'); // Output: `false`
matchHostname(url, 'example.com', true); // Output: `true`
matchPathname()
Type: (url: URL, pathname?: string, allowWildcard = false) => boolean
Matches a given URL's pathname against a specified pattern, with optional support for wildcards.
const testURL = new URL('https://example.com/images/photo.jpg');
matchPathname(testURL, '/images/photo.jpg'); // Output: `true`
matchPathname(testURL, '/images/'); // Output: `false`
matchPathname(testURL, '/images/*', true); // Output: `true`
matchPattern()
Type: (url: URL, remotePattern: RemotePattern) => boolean
Evaluates whether a given URL matches the specified remote pattern based on protocol, hostname, port, and pathname.
const url = new URL('https://images.example.com/photos/test.jpg');
const remotePattern = {
protocol: 'https',
hostname: 'images.example.com',
pathname: '/photos/**', // Allow all files under /photos/
};
matchPattern(url, remotePattern); // Output: `true`
matchPort()
Type: (url: URL, port?: string) => boolean
Default: true
Checks if the given URL's port matches the specified port. If no port is provided, it returns true.
const urlWithPort = new URL('https://example.com:8080/resource');
const urlWithoutPort = new URL('https://example.com/resource');
matchPort(urlWithPort, '8080'); // Output: `true`
matchPort(urlWithoutPort, '8080'); // Output: `false`
matchProtocol()
Type: (url: URL, protocol?: string) => boolean
Default: true
Compares the protocol of the provided URL with a specified protocol. This returns true if the protocol matches or if no protocol is provided.
const secureUrl = new URL('https://example.com/resource');
const regularUrl = new URL('http://example.com/resource');
matchProtocol(secureUrl, 'https'); // Output: `true`
matchProtocol(regularUrl, 'https'); // Output: `false`
isESMImportedImage()
Type: (src: ImageMetadata | string) => boolean
Determines if the given source is an ECMAScript Module (ESM) imported image.
const imageMetadata = {
src: '/images/photo.jpg',
width: 800,
height: 600,
format: 'jpg',
};
const filePath = '/images/photo.jpg';
isESMImportedImage(imageMetadata); // Output: `true`
isESMImportedImage(filePath); // Output: `false`
isRemoteImage()
Type: (src: ImageMetadata | string) => boolean
Determines if the provided source is a remote image URL in the form of a string.
const imageUrl = 'https://example.com/images/photo.jpg';
const localImage = {
src: '/images/photo.jpg',
width: 800,
height: 600,
format: 'jpg',
};
isRemoteImage(imageUrl); // Output: `true`
isRemoteImage(localImage); // Output: `false`
resolveSrc()
Type: (src: UnresolvedImageTransform['src']) => Promise<string | ImageMetadata>
Returns the image source. This function ensures that if src is a Promise (e.g., a dynamic import()), it is awaited and the correct src is extracted. If src is already a resolved value, it is returned as-is.
const resolvedLocal = await resolveSrc(localImage);
// Example value: `{ src: '/@fs/home/username/dev/astro-project/src/images/photo.jpg', width: 800, height: 600, format: 'jpg' }`
const resolvedRemote = await resolveSrc("https://example.com/remote-img.jpg");
// Value: `"https://example.com/remote-img.jpg"`
const resolvedDynamic = await resolveSrc(import("./images/dynamic-image.jpg"))
// Example value: `{ src: '/@fs/home/username/dev/astro-project/src/images/dynamic-image.jpg', width: 800, height: 600, format: 'jpg' }`
imageMetadata()
Type: (data: Uint8Array, src?: string) => Promise<Omit<ImageMetadata, 'src' | 'fsPath'>>
Extracts image metadata such as dimensions, format, and orientation from the provided image data.
const binaryImage = new Uint8Array([/* ...binary image data... */]);
const sourcePath = '/images/photo.jpg';
const metadata = await imageMetadata(binaryImage, sourcePath);
// Example value:
// {
// width: 800,
// height: 600,
// format: 'jpg',
// orientation: undefined
// }
emitImageMetadata()
Type: (id: string | undefined, fileEmitter?: Rollup.EmitFile) => Promise<(ImageMetadata & { contents?: Buffer }) | undefined>
Processes an image file and emits its metadata and optionally its contents. In build mode, the function uses fileEmitter to generate an asset reference. In development mode, it resolves to a local file URL with query parameters for metadata.
const imageId = '/images/photo.jpg';
const metadata = await emitImageMetadata(imageId);
// Example value:
// {
// src: '/@fs/home/username/dev/astro-project/src/images/photo.jpg?origWidth=800&origHeight=600&origFormat=jpg',
// width: 800,
// height: 600,
// format: 'jpg',
// contents: Uint8Array([...])
// }
emitClientAsset()
Type: (pluginContext: Rollup.PluginContext, options: Rollup.EmitFile) => string
Emits a client asset that will be moved to the client directory for assets (e.g. dist/client/_astro/) during SSR builds. This function is intended for integration authors who need to emit assets (such as images) from server-rendered content that should be available on the client.
Use this instead of Rollup pluginContext.emitFile() directly when working in a Vite plugin context and you need the emitted asset to be moved to the client output directory.
function myVitePlugin() {
return {
name: 'my-plugin',
transform(code, id) {
const handle = emitClientAsset(this, {
type: 'asset',
name: 'my-image.png',
source: imageBuffer,
});
// Returns the asset handle similar to `emitFile()`
}
}
}
getOrigQueryParams()
Type: (params: URLSearchParams) => Pick<ImageMetadata, 'width' | 'height' | 'format'> | undefined
Retrieves the width, height, and format of an image from a URLSearchParams object. If any of these parameters are missing or invalid, the function returns undefined.
const url = new URL('https://example.com/image.jpg?width=800&height=600&format=jpg');
const origParams = getOrigQueryParams(url.searchParams);
// Example value:
// {
// width: 800,
// height: 600,
// format: 'jpg'
// }
inferRemoteSize()
Type: (url: string) => Promise<Omit<ImageMetadata, 'src' | 'fsPath'>>
Infers the dimensions of a remote image by streaming its data and analyzing it progressively until sufficient metadata is available.
const remoteImageUrl = 'https://example.com/image.jpg';
const imageSize = await inferRemoteSize(remoteImageUrl);
// Example value:
// {
// width: 1920,
// height: 1080,
// format: 'jpg'
// }
propsToFilename()
Type: (filePath: string, transform: ImageTransform, hash: string) => string
Generates a formatted filename for an image based on its source path, transformation properties, and a unique hash.
The formatted filename follows this structure:
<prefixDirname>/<baseFilename>_<hash><outputExtension>
prefixDirname: If the image is an ESM imported image, this is the directory name of the original file path; otherwise, it will be an empty string.baseFilename: The base name of the file or a hashed short name if the file is adata:URI.hash: A unique hash string generated to distinguish the transformed file.outputExtension: The desired output file extension derived from thetransform.formator the original file extension.
const filePath = '/images/photo.jpg';
const transform = { format: 'png', src: filePath };
const hash = 'abcd1234';
const filename = propsToFilename(filePath, transform, hash);
// Example value: '/images/photo_abcd1234.png'
hashTransform()
Type: (transform: ImageTransform, imageService: string, propertiesToHash: string[]) => string
Transforms the provided transform object into a hash string based on selected properties and the specified imageService.
const transform = {
src: '/images/photo.jpg',
width: 800,
height: 600,
format: 'jpg',
};
const imageService = 'astro/assets/services/sharp';
const propertiesToHash = ['width', 'height', 'format'];
const hash = hashTransform(transform, imageService, propertiesToHash);
// Example value: 'd41d8cd98f00b204e9800998ecf8427e'
astro types
GetImageResult
Type: object
Describes the result of the transformation after the call to getImage().
GetImageResult.attributes
Type: Record<string, any>
Defines the additional HTML attributes needed to render the image (e.g. width, height, style).
GetImageResult.options
Type: ImageTransform
Describes the transformation settings after validation.
GetImageResult.rawOptions
Type: ImageTransform
Describes the original transformation settings.
GetImageResult.src
Type: string
The path to the generated image.
GetImageResult.srcSet
Type: { values: { transform: ImageTransform; descriptor?: string; attributes?: Record<string, any>; url: string; }[]; attribute: string; }
An object describing how to render the srcset attribute.
GetImageResult.srcSet.values
Type: { transform: ImageTransform; descriptor?: string; attributes?: Record<string, any>; url: string; }[]
An array of generated values where each entry includes a URL and a size descriptor. This can be used to manually generate the value of the srcset attribute.
GetImageResult.srcSet.attribute
Type: string
A value ready to use in the srcset attribute.
ImageTransform
Type: object
Defines the options accepted by the image transformation service. This contains a required src property, optional predefined properties, and any additional properties required by the image service:
ImageTransform.src
Type: ImageMetadata | string
Defines the path to a local image in the public directory, the URL of a remote image, or the data from an imported image.
ImageTransform.width
Type: number | undefined
The width of the image.
ImageTransform.height
Type: number | undefined
The height of the image.
ImageTransform.widths
Type: number[] | undefined
A list of widths to generate for the image.
ImageTransform.densities
Type: (number | `${number}x`)[] | undefined
A list of pixel densities to generate for the image.
ImageTransform.quality
Type: ImageQuality | undefined
The desired quality for the output image.
ImageTransform.format
Type: ImageOutputFormat | undefined
The desired format for the output image.
ImageTransform.fit
Type: 'fill' | 'contain' | 'cover' | 'none' | 'scale-down' | string | undefined
Defines a list of allowed values for the object-fit CSS property, extensible with any string.
ImageTransform.position
Type: string | undefined
Controls the value for the object-position CSS property.
UnresolvedImageTransform
Type: Omit<ImageTransform, "src"> & { src: ImageMetadata | string | Promise<{ default: ImageMetadata }>; inferSize?: boolean; }
Represents an image with transformation options. This contains the same properties as the ImageTransform type with a different src type and an additional inferSize property.
UnresolvedImageTransform.src
Type: ImageMetadata | string | Promise<{ default: ImageMetadata }>
The path to an image imported or located in the public directory, or the URL of a remote image.
UnresolvedImageTransform.inferSize
Type: boolean
Determines whether the width and height of the image should be inferred.
inferSize attribute available on <Image />.
ImageMetadata
Type: { src: string; width: number; height: number; format: ImageInputFormat; orientation?: number; }
Describes the data collected during image import. This contains the following properties:
ImageMetadata.src
Type: string
The absolute path of the image on the filesystem.
ImageMetadata.width
Type: number
The width of the image.
ImageMetadata.height
Type: number
The height of the image.
ImageMetadata.format
Type: ImageInputFormat
The format of the image.
ImageMetadata.orientation
Type: number
The image orientation when its metadata contains this information.
ImageInputFormat
Type: "jpeg" | "jpg" | "png" | "tiff" | "webp" | "gif" | "svg" | "avif"
Describes a union of supported formats for imported images.
ImageOutputFormat
Type: string | "jpeg" | "jpg" | "png" | "webp" | "svg" | "avif"
Specifies the format for output images. This can be a predefined literal or any string.
ImageQuality
Type: ImageQualityPreset | number
Represents the perceptual quality of the output image as a union of predefined literals, a string, or a number.
ImageQualityPreset
Type: string | "low" | "mid" | "high" | "max"
Defines the available presets to control image quality, extensible with any string.
RemotePattern
Type: { hostname?: string; pathname?: string; protocol?: string; port?: string; }
Describes a remote host through four optional properties: hostname, pathname, protocol, and port.
ImageService
Type: ExternalImageService | LocalImageService
Defines the hooks that a local or external image service must provide.
ExternalImageService
Type: object
Defines the hooks that an external image transformation service must provide. This requires a getUrl() hook and supports three additional hooks.
LocalImageService
Type: object
Defines the hooks that a local image transformation service must provide. This requires getUrl(), parseUrl(), and transform() hooks, and supports additional hooks.
ImageServiceConfig
Type: { entrypoint: 'astro/assets/services/sharp' | string; config?: T; }
Describes the configuration object for an image service. This contains the following properties:
ImageServiceConfig.entrypoint
Type: 'astro/assets/services/sharp' | string
A package or path to the image service module. This can be Astro's built-in Sharp service or a third-party service.
ImageServiceConfig.config
Type: Record<string, any>
A configuration object passed to the image service. The shape depends on the specific service being used.