Astro provides several built-in modules that you can import into your project. This page documents the core modules available in every Astro project.
astro:assets
The astro:assets module provides built-in components and helper functions for optimizing and displaying images.
Imports
import {
Image,
Picture,
getImage,
inferRemoteSize,
getConfiguredImageService,
imageConfig,
} from 'astro:assets';
<Image />
The <Image /> component optimizes and transforms images.
src/components/MyComponent.astro
---
import { Image } from 'astro:assets';
import myImage from "../assets/my_image.png";
---
<Image src={myImage} alt="A description of my image." />
Props
src
ImageMetadata | string | Promise<{ default: ImageMetadata }>
required
The image file. For local images in src/, import the image. For images in public/, use the file path. For remote images, use the full URL.
Descriptive alt text for the image.
The desired width of the image. Required for images in public/.
The desired height of the image. Required for images in public/.
format
'avif' | 'jpeg' | 'jpg' | 'png' | 'svg' | 'webp'
The output image format. Defaults to .webp.
quality
'low' | 'mid' | 'high' | 'max' | number
The image quality. Can be a preset or a number from 0-100.
densities
Array<number | `${number}x`>
A list of pixel densities to generate for the image. Used to generate a srcset attribute.
A list of widths to generate for the image. Used to generate a srcset attribute. Must be used with sizes.
Specifies the layout width of the image for each of a list of media conditions. Must be provided when specifying widths.
Automatically infer width and height for remote images.
Automatically sets loading, decoding, and fetchpriority attributes to optimal values for above-the-fold images.
Background color to use when flattening images with transparency. Especially useful when converting to formats that don’t support transparency like JPEG.
Example: Local image
---
import { Image } from 'astro:assets';
import myImage from '../assets/my_image.png';
---
<Image src={myImage} alt="A description of my image." />
Example: Remote image
---
import { Image } from 'astro:assets';
---
<Image
src="https://example.com/remote-image.jpg"
alt="A description of my image."
width="200"
height="150"
/>
Example: Image with densities
---
import { Image } from 'astro:assets';
import myImage from '../assets/my_image.png';
---
<Image
src={myImage}
width={myImage.width / 2}
densities={[1.5, 2]}
alt="A description of my image."
/>
<Picture />
The <Picture /> component generates an optimized image with multiple formats and/or sizes.
---
import { Picture } from 'astro:assets';
import myImage from "../assets/my_image.png";
---
<Picture src={myImage} formats={['avif', 'webp']} alt="A description of my image." />
Props
<Picture /> accepts all the properties of <Image />, plus:
formats
Array<'avif' | 'jpeg' | 'jpg' | 'png' | 'svg' | 'webp'>
default:"['webp']"
An array of image formats to use for the <source> tags. Entries will be added in the order listed.
fallbackFormat
'avif' | 'gif' | 'jpeg' | 'jpg' | 'png' | 'svg' | 'webp'
Format to use as a fallback value for the <img> tag. Defaults to .png for static images, .gif for animated images, and .svg for SVG files.
pictureAttributes
HTMLAttributes<'picture'>
An object of attributes to be added to the <picture> tag.
Responsive Image Properties
Setting the layout property creates a responsive image.
layout
'constrained' | 'full-width' | 'fixed' | 'none'
default:"'none'"
Defines how the image should resize when its container changes size.
constrained - The image will scale down to fit the container but won’t scale up beyond its original dimensions
full-width - The image will scale to fit the width of the container
fixed - The image will maintain the requested dimensions and not resize
none - The image will not be responsive
fit
'contain' | 'cover' | 'fill' | 'none' | 'scale-down'
default:"'cover'"
Defines how a responsive image should be cropped if its aspect ratio is changed. Values match CSS object-fit.
Defines the position of the image crop for a responsive image. Values match CSS object-position.
Example: Responsive image
---
import { Image } from 'astro:assets';
import myImage from '../assets/my_image.png';
---
<Image
src={myImage}
alt="A description of my image."
layout='constrained'
width={800}
height={600}
/>
getImage()
getImage()
(options: UnresolvedImageTransform) => Promise<GetImageResult>
Generates images destined to be used somewhere other than directly in HTML.
Image transformation options (same as <Image /> props except alt).
The result of the image transformation.The path to the generated image.
Additional HTML attributes needed to render the image (width, height, style, etc.).
The transformation settings after validation.
src/components/Background.astro
---
import { getImage } from "astro:assets";
import myBackground from "../background.png"
const optimizedBackground = await getImage({src: myBackground, format: 'avif'})
---
<div style={`background-image: url(${optimizedBackground.src});`}><slot /></div>
inferRemoteSize()
inferRemoteSize()
(url: string) => Promise<Omit<ImageMetadata, 'src' | 'fsPath'>>
Automatically infers the width and height of a remote image.
The URL of the remote image.
import { inferRemoteSize } from 'astro:assets';
const { width, height } = await inferRemoteSize("https://example.com/cat.png");
getConfiguredImageService()
() => Promise<ImageService>
Retrieves the resolved image service.
imageConfig
The configuration options for images set by the user and merged with all defaults.
astro:content
The astro:content module provides APIs to configure and query your Markdown or MDX documents.
Imports
import {
defineCollection,
getCollection,
getEntry,
getEntries,
reference,
render
} from 'astro:content';
defineCollection()
defineCollection()
(input: CollectionConfig) => CollectionConfig
A utility to configure a collection in a src/content.config.* file.
loader
Loader | () => Promise<Array | Record>
required
Allows you to load data from any source, local or remote, into content collections.
schema
ZodType | (context: SchemaContext) => ZodType
An optional Zod object to configure the type and shape of document frontmatter.
import { z, defineCollection } from 'astro:content';
import { glob } from 'astro/loaders';
const blog = defineCollection({
loader: glob({ pattern: '**/*.md', base: './src/data/blog' }),
schema: z.object({
title: z.string(),
permalink: z.string().optional(),
}),
});
export const collections = { blog };
reference()
reference()
(collection: string) => ZodEffects<ZodString, { collection, id: string }>
Defines a relationship from one collection to another.
The name of the collection being referenced.
import { defineCollection, reference, z } from 'astro:content';
import { glob } from 'astro/loaders';
const blog = defineCollection({
loader: glob({ pattern: '**/*.md', base: './src/data/blog' }),
schema: z.object({
author: reference('authors'),
relatedPosts: z.array(reference('blog')),
})
});
const authors = defineCollection({
loader: file("src/data/authors.json"),
schema: z.object({ /* ... */ })
});
export const collections = { blog, authors };
getCollection()
getCollection()
(collection: string, filter?: (entry: CollectionEntry) => boolean) => Promise<CollectionEntry[]>
Retrieves a list of content collection entries by collection name.
The name of the collection to query.
filter
(entry: CollectionEntry) => boolean
An optional function to filter entries by their properties.
An array of collection entries.A unique ID for the entry.
The name of the collection.
Frontmatter properties inferred from the collection schema.
The raw, uncompiled body of the document.
---
import { getCollection } from 'astro:content';
// Get all blog posts
const allBlogPosts = await getCollection('blog');
// Only return posts with `draft: true`
const draftBlogPosts = await getCollection('blog', ({ data }) => {
return data.draft === true;
});
---
getEntry()
getEntry()
(collection: string, id: string) => Promise<CollectionEntry | undefined>
Retrieves a single collection entry by collection name and entry ID.
The name of the collection.
CollectionEntry | undefined
The collection entry, or undefined if not found.
---
import { getEntry } from 'astro:content';
const enterprisePost = await getEntry('blog', 'enterprise');
const picardProfile = await getEntry('captains', 'picard');
// Get referenced entry
const enterpriseCaptainProfile = await getEntry(enterprisePost.data.captain);
---
getEntries()
getEntries()
(entries: Array<{ collection: string, id: string }>) => Promise<CollectionEntry[]>
Retrieves multiple collection entries from the same collection.
entries
Array<{ collection: string, id: string }>
required
An array of entry references to retrieve.
An array of collection entries.
---
import { getEntries, getEntry } from 'astro:content';
const enterprisePost = await getEntry('blog', 'enterprise');
const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts);
---
render()
render()
(entry: CollectionEntry) => Promise<RenderedEntry>
Compiles a given entry for rendering.
The collection entry to render.
A component used to render the document’s contents in an Astro file.
headings
Array<{ depth: number; slug: string; text: string }>
A generated list of headings.
The modified frontmatter object after any remark or rehype plugins have been applied.
---
import { getEntry, render } from 'astro:content';
const entry = await getEntry('blog', 'entry-1');
if (!entry) {
throw new Error('Could not find blog post 1');
}
const { Content, headings, remarkPluginFrontmatter } = await render(entry);
---
<Content />
astro:actions
The astro:actions module provides utilities for defining and calling type-safe backend actions.
Imports
import {
defineAction,
actions,
ActionError,
isInputError,
isActionError,
getActionContext,
getActionPath,
ACTION_QUERY_PARAMS
} from 'astro:actions';
defineAction()
defineAction()
(config: { accept?, input?, handler }) => ActionClient
Define a new server action with type-safe inputs and outputs.
accept
'form' | 'json'
default:"'json'"
The expected input format.
Optional Zod validator for input validation.
handler
(input, context: ActionAPIContext) => any
Server logic to run when the action is called.
import { defineAction } from 'astro:actions';
import { z } from 'astro/zod';
export const server = {
getGreeting: defineAction({
input: z.object({ name: z.string() }),
handler: async (input) => {
return `Hello, ${input.name}!`;
}
})
};
actions
actions
Record<string, ActionClient>
Object containing all your defined actions. Used to call actions from client code.
<script>
import { actions } from 'astro:actions';
const { data, error } = await actions.getGreeting({ name: 'World' });
</script>
ActionError
Error class for throwing custom errors from action handlers.
import { ActionError } from 'astro:actions';
throw new ActionError({
code: 'NOT_FOUND',
message: 'User not found'
});
astro:middleware
The astro:middleware module provides utilities for creating middleware functions with type safety.
Imports
import { defineMiddleware, sequence } from 'astro:middleware';
defineMiddleware()
defineMiddleware()
(fn: MiddlewareHandler) => MiddlewareHandler
Define middleware with proper TypeScript types for the context object.
import { defineMiddleware } from 'astro:middleware';
export const onRequest = defineMiddleware(async (context, next) => {
// Add custom logic
context.locals.user = await getUser(context.request);
return next();
});
sequence()
sequence()
(...handlers: MiddlewareHandler[]) => MiddlewareHandler
Chain multiple middleware functions to run in sequence.
import { sequence } from 'astro:middleware';
const auth = defineMiddleware(async (context, next) => { /* ... */ });
const logging = defineMiddleware(async (context, next) => { /* ... */ });
export const onRequest = sequence(auth, logging);
astro:transitions
The astro:transitions module provides the View Transitions router and animation utilities.
Imports
import { ClientRouter, fade, slide } from 'astro:transitions';
import { navigate, supportsViewTransitions } from 'astro:transitions/client';
ClientRouter
Component that enables client-side routing with view transitions.
---
import { ClientRouter } from 'astro:transitions';
---
<head>
<ClientRouter />
</head>
Animation functions
fade()
(options?) => TransitionAnimation
Built-in fade animation for view transitions.
slide()
(options?) => TransitionAnimation
Built-in slide animation for view transitions.
navigate()
navigate()
(href: string, options?) => void
Programmatically navigate to a new page with view transitions.
<script>
import { navigate } from 'astro:transitions/client';
navigate('/about', { history: 'push' });
</script>
astro:i18n
The astro:i18n module provides internationalization utilities for working with localized URLs.
Imports
import {
getRelativeLocaleUrl,
getAbsoluteLocaleUrl,
getRelativeLocaleUrlList,
getAbsoluteLocaleUrlList,
getPathByLocale,
getLocaleByPath
} from 'astro:i18n';
getRelativeLocaleUrl()
getRelativeLocaleUrl()
(locale: string, path?: string, options?) => string
Get a relative URL for a specific locale.
---
import { getRelativeLocaleUrl } from 'astro:i18n';
const frenchUrl = getRelativeLocaleUrl('fr', 'getting-started');
// Returns: /fr/getting-started
---
getAbsoluteLocaleUrl()
getAbsoluteLocaleUrl()
(locale: string, path?: string, options?) => string
Get an absolute URL for a specific locale (requires site config).
astro:env
The astro:env module provides utilities for accessing environment variables with type safety.
Imports
import { getSecret } from 'astro:env/server';
getSecret()
getSecret()
(key: string) => string | undefined
Safely access environment variables on the server.
import { getSecret } from 'astro:env/server';
const apiKey = getSecret('API_KEY');
astro:config
The astro:config module provides access to your Astro configuration at runtime.
Imports
// Client-side config
import { site, base, trailingSlash } from 'astro:config/client';
// Server-side config (includes all client config)
import { srcDir, outDir, publicDir } from 'astro:config/server';
These modules expose your configuration as constants you can use in your code.
astro/zod
Re-exports the Zod validation library for use in content collections and actions.
import { z } from 'astro/zod';
const schema = z.object({
title: z.string(),
pubDate: z.date(),
tags: z.array(z.string()),
});