W↓
All docs
🔑
Sign Up/Sign In
docs.astro.build/en/reference/
Public Link
Apr 6, 2025, 10:48:04 AM - complete - 400.4 kB
Starting URLs:
https://docs.astro.build/en/reference/astro-syntax/
Crawl Prefixes:
https://docs.astro.build/en/reference/
Max Pages:
1000
## Page: https://docs.astro.build/en/reference/astro-syntax/ Astro component syntax is a superset of HTML. The syntax was designed to feel familiar to anyone with experience writing HTML or JSX, and adds support for including components and JavaScript expressions. ## JSX-like Expressions Section titled JSX-like Expressions You can define local JavaScript variables inside of the frontmatter component script between the two code fences (`---`) of an Astro component. You can then inject these variables into the component’s HTML template using JSX-like expressions! Local variables can be added into the HTML using the curly braces syntax: ---const name = "Astro";---<div> <h1>Hello {name}!</h1> <!-- Outputs <h1>Hello Astro!</h1> --></div> ### Dynamic Attributes Section titled Dynamic Attributes Local variables can be used in curly braces to pass attribute values to both HTML elements and components: ---const name = "Astro";---<h1 class={name}>Attribute expressions are supported</h1><MyComponent templateLiteralNameAttribute={`MyNameIs${name}`} /> Local variables can be used in JSX-like functions to produce dynamically-generated HTML elements: ---const items = ["Dog", "Cat", "Platypus"];---<ul> {items.map((item) => ( <li>{item}</li> ))}</ul> Astro can conditionally display HTML using JSX logical operators and ternary expressions. ---const visible = true;---{visible && <p>Show me!</p>}{visible ? <p>Show me!</p> : <p>Else show me!</p>} You can also use dynamic tags by assigning an HTML tag name to a variable or with a component import reassignment: ---import MyComponent from "./MyComponent.astro";const Element = 'div'const Component = MyComponent;---<Element>Hello!</Element> <!-- renders as <div>Hello!</div> --><Component /> <!-- renders as <MyComponent /> --> When using dynamic tags: * **Variable names must be capitalized.** For example, use `Element`, not `element`. Otherwise, Astro will try to render your variable name as a literal HTML tag. * **Hydration directives are not supported.** When using `client:*` hydration directives, Astro needs to know which components to bundle for production, and the dynamic tag pattern prevents this from working. * **The define:vars directive is not supported.** If you cannot wrap the children with an extra element (e.g `<div>`), then you can manually add a ``style={`--myVar:${value}`}`` to your Element. Astro supports `<> </>` notation and also provides a built-in `<Fragment />` component. This component can be useful to avoid wrapper elements when adding `set:*` directives to inject an HTML string. The following example renders paragraph text using the `<Fragment />` component: ---const htmlString = '<p>Raw HTML content</p>';---<Fragment set:html={htmlString} /> ### Differences between Astro and JSX Section titled Differences between Astro and JSX Astro component syntax is a superset of HTML. It was designed to feel familiar to anyone with HTML or JSX experience, but there are a couple of key differences between `.astro` files and JSX. In Astro, you use the standard `kebab-case` format for all HTML attributes instead of the `camelCase` used in JSX. This even works for `class`, which is not supported by React. <div className="box" dataValue="3" /><div class="box" data-value="3" /> #### Multiple Elements Section titled Multiple Elements An Astro component template can render multiple elements with no need to wrap everything in a single `<div>` or `<>`, unlike JavaScript or JSX. ---// Template with multiple elements---<p>No need to wrap elements in a single containing element.</p><p>Astro supports multiple root elements in a template.</p> In Astro, you can use standard HTML comments or JavaScript-style comments. ------<!-- HTML comment syntax is valid in .astro files -->{/* JS comment syntax is also valid */} ## Component utilities Section titled Component utilities `Astro.slots` contains utility functions for modifying an Astro component’s slotted children. #### `Astro.slots.has()` Section titled Astro.slots.has() **Type:** `(slotName: string) => boolean` You can check whether content for a specific slot name exists with `Astro.slots.has()`. This can be useful when you want to wrap slot contents but only want to render the wrapper elements when the slot is being used. ------<slot />{Astro.slots.has('more') && ( <aside> <h2>More</h2> <slot name="more" /> </aside>)} #### `Astro.slots.render()` Section titled Astro.slots.render() **Type:** `(slotName: string, args?: any[]) => Promise<string>` You can asynchronously render the contents of a slot to a string of HTML using `Astro.slots.render()`. ---const html = await Astro.slots.render('default');---<Fragment set:html={html} /> `Astro.slots.render()` optionally accepts a second argument: an array of parameters that will be forwarded to any function children. This can be useful for custom utility components. For example, this `<Shout />` component converts its `message` prop to uppercase and passes it to the default slot: ---const message = Astro.props.message.toUpperCase();let html = '';if (Astro.slots.has('default')) { html = await Astro.slots.render('default', [message]);}---<Fragment set:html={html} /> A callback function passed as `<Shout />`’s child will receive the all-caps `message` parameter: ---import Shout from "../components/Shout.astro";---<Shout message="slots!"> {(message) => <div>{message}</div>}</Shout><!-- renders as <div>SLOTS!</div> --> Callback functions can be passed to named slots inside a wrapping HTML element tag with a `slot` attribute. This element is only used to transfer the callback to a named slot and will not be rendered onto the page. <Shout message="slots!"> <fragment slot="message"> {(message) => <div>{message}</div>} </fragment></Shout> Use a standard HTML element for the wrapping tag or any lowercase tag (e.g. `<fragment>` instead of `<Fragment />`) that will not be interpreted as a component. Do not use the HTML `<slot>` element as this will be interpreted as an Astro slot. `Astro.self` allows Astro components to be recursively called. This behavior lets you render an Astro component from within itself by using `<Astro.self>` in the component template. This can help iterate over large data stores and nested data structures. ---const { items } = Astro.props;---<ul class="nested-list"> {items.map((item) => ( <li> <!-- If there is a nested data-structure we render `<Astro.self>` --> <!-- and can pass props through with the recursive call --> {Array.isArray(item) ? ( <Astro.self items={item} /> ) : ( item )} </li> ))}</ul> This component could then be used like this: ---import NestedList from './NestedList.astro';---<NestedList items={['A', ['B', 'C'], 'D']} /> And would render HTML like this: <ul class="nested-list"> <li>A</li> <li> <ul class="nested-list"> <li>B</li> <li>C</li> </ul> </li> <li>D</li></ul> --- ## Page: https://docs.astro.build/en/reference/directives-reference/ **Template directives** are a special kind of HTML attribute available inside of any Astro component template (`.astro` files), and some can also be used in `.mdx` files. Template directives are used to control an element or component’s behavior in some way. A template directive could enable some compiler feature that makes your life easier (like using `class:list` instead of `class`). Or, a directive could tell the Astro compiler to do something special with that component (like hydrating with `client:load`). This page describes all of the template directives available to you in Astro, and how they work. For a template directive to be valid, it must: * Include a colon `:` in its name, using the form `X:Y` (ex: `client:load`). * Be visible to the compiler (ex: `<X {...attr}>` would not work if `attr` contained a directive). Some template directives, but not all, can take a custom value: * `<X client:load />` (takes no value) * `<X class:list={['some-css-class']} />` (takes an array) A template directive is never included directly in the final HTML output of a component. ## Common Directives Section titled Common Directives `class:list={...}` takes an array of class values and converts them into a class string. This is powered by @lukeed’s popular clsx helper library. `class:list` takes an array of several different possible value kinds: * `string`: Added to the element `class` * `Object`: All truthy keys are added to the element `class` * `Array`: flattened * `false`, `null`, or `undefined`: skipped <!-- This --><span class:list={[ 'hello goodbye', { world: true }, [ 'friend' ] ]} /><!-- Becomes --><span class="hello goodbye world friend"></span> `set:html={string}` injects an HTML string into an element, similar to setting `el.innerHTML`. **The value is not automatically escaped by Astro!** Be sure that you trust the value, or that you have escaped it manually before passing it to the template. Forgetting to do this will open you up to Cross Site Scripting (XSS) attacks. ---const rawHTMLString = "Hello <strong>World</strong>"---<h1>{rawHTMLString}</h1> <!-- Output: <h1>Hello <strong>World</strong></h1> --><h1 set:html={rawHTMLString} /> <!-- Output: <h1>Hello <strong>World</strong></h1> --> You can also use `set:html` on a `<Fragment>` to avoid adding an unnecessary wrapper element. This can be especially useful when fetching HTML from a CMS. ---const cmsContent = await fetchHTMLFromMyCMS();---<Fragment set:html={cmsContent}> `set:html={Promise<string>}` injects an HTML string into an element that is wrapped in a Promise. This can be used to inject HTML stored externally, such as in a database. ---import api from '../db/api.js';---<article set:html={api.getArticle(Astro.props.id)}></article> `set:html={Promise<Response>}` injects a Response into an element. This is most helpful when using `fetch()`. For example, fetching old posts from a previous static-site generator. <article set:html={fetch('http://example/old-posts/making-soup.html')}></article> `set:html` can be used on any tag and does not have to include HTML. For example, use with `JSON.stringify()` on a `<script>` tag to add a JSON-LD schema to your page. <script type="application/ld+json" set:html={JSON.stringify({ "@context": "https://schema.org/", "@type": "Person", name: "Houston", hasOccupation: { "@type": "Occupation", name: "Astronaut" }})}/> `set:text={string}` injects a text string into an element, similar to setting `el.innerText`. Unlike `set:html`, the `string` value that is passed is automatically escaped by Astro. This is equivalent to just passing a variable into a template expression directly (ex: `<div>{someText}</div>`) and therefore this directive is not commonly used. ## Client Directives Section titled Client Directives These directives control how UI Framework components are hydrated on the page. By default, a UI Framework component is not hydrated in the client. If no `client:*` directive is provided, its HTML is rendered onto the page without JavaScript. A client directive can only be used on a UI framework component that is directly imported into a `.astro` component. Hydration directives are not supported when using dynamic tags and custom components passed via the `components` prop. * **Priority:** High * **Useful for:** Immediately-visible UI elements that need to be interactive as soon as possible. Load and hydrate the component JavaScript immediately on page load. <BuyButton client:load /> * **Priority:** Medium * **Useful for:** Lower-priority UI elements that don’t need to be immediately interactive. Load and hydrate the component JavaScript once the page is done with its initial load and the `requestIdleCallback` event has fired. If you are in a browser that doesn’t support `requestIdleCallback`, then the document `load` event is used. <ShowHideButton client:idle /> **Added in:** `astro@4.15.0` The maximum time to wait, in milliseconds, before hydrating the component, even if the page is not yet done with its initial load. This allows you to pass a value for the `timeout` option from the `requestIdleCallback()` specification. This means you can delay hydration for lower-priority UI elements with more control to ensure your element is interactive within a specified time frame. <ShowHideButton client:idle={{timeout: 500}} /> * **Priority:** Low * **Useful for:** Low-priority UI elements that are either far down the page (“below the fold”) or so resource-intensive to load that you would prefer not to load them at all if the user never saw the element. Load and hydrate the component JavaScript once the component has entered the user’s viewport. This uses an `IntersectionObserver` internally to keep track of visibility. <HeavyImageCarousel client:visible /> #### `client:visible={{rootMargin}}` Section titled client:visible={{rootMargin}} **Added in:** `astro@4.1.0` Optionally, a value for `rootMargin` can be passed to the underlying `IntersectionObserver`. When `rootMargin` is specified, the component JavaScript will hydrate when a specified margin (in pixels) around the component enters the viewport, rather than the component itself. <HeavyImageCarousel client:visible={{rootMargin: "200px"}} /> Specifying a `rootMargin` value can reduce layout shifts (CLS), allow more time for a component to hydrate on slower internet connections, and make components interactive sooner, enhancing the stability and responsiveness of the page. * **Priority:** Low * **Useful for:** Sidebar toggles, or other elements that might only be visible on certain screen sizes. `client:media={string}` loads and hydrates the component JavaScript once a certain CSS media query is met. <SidebarToggle client:media="(max-width: 50em)" /> `client:only={string}` **skips** HTML server rendering, and renders only on the client. It acts similarly to `client:load` in that it loads, renders, and hydrates the component immediately on page load. **You must pass the component’s correct framework as a value!** Because Astro doesn’t run the component during your build / on the server, Astro doesn’t know what framework your component uses unless you tell it explicitly. <SomeReactComponent client:only="react" /><SomePreactComponent client:only="preact" /><SomeSvelteComponent client:only="svelte" /><SomeVueComponent client:only="vue" /><SomeSolidComponent client:only="solid-js" /> #### Display loading content Section titled Display loading content For components that render only on the client, it is also possible to display fallback content while they are loading. Use `slot="fallback"` on any child element to create content that will be displayed only until your client component is available: <ClientComponent client:only="vue"> <div slot="fallback">Loading</div></ClientComponent> ### Custom Client Directives Section titled Custom Client Directives Since Astro 2.6.0, integrations can also add custom `client:*` directives to change how and when components should be hydrated. Visit the `addClientDirective` API page to learn more about creating a custom client directive. ## Server Directives Section titled Server Directives These directives control how server island components are rendered. The `server:defer` directive transforms the component into a server island, causing it to be rendered on demand, outside the scope of the rest of the page rendering. <Avatar server:defer /> ## Script & Style Directives Section titled Script & Style Directives These directives can only be used on HTML `<script>` and `<style>` tags, to control how your client-side JavaScript and CSS are handled on the page. By default, Astro automatically scopes `<style>` CSS rules to the component. You can opt-out of this behavior with the `is:global` directive. `is:global` makes the contents of a `<style>` tag apply globally on the page when the component is included. This disables Astro’s CSS scoping system. This is equivalent to wrapping all of the selectors within a `<style>` tag with `:global()`. You can combine `<style>` and `<style is:global>` together in the same component, to create some global style rules while still scoping most of your component CSS. See the Styling & CSS page for more details about how global styles work. <style is:global> body a { color: red; }</style> By default, Astro will process, optimize, and bundle any `<script>` and `<style>` tags that it sees on the page. You can opt-out of this behavior with the `is:inline` directive. `is:inline` tells Astro to leave the `<script>` or `<style>` tag as-is in the final output HTML. The contents will not be processed, optimized, or bundled. This limits some Astro features, like importing an npm package or using a compile-to-CSS language like Sass. The `is:inline` directive means that `<style>` and `<script>` tags: * Will not be bundled into an external file. This means that attributes like `defer` which control the loading of an external file will have no effect. * Will not be deduplicated—the element will appear as many times as it is rendered. * Will not have its `import`/`@import`/`url()` references resolved relative to the `.astro` file. * Will be rendered in the final output HTML exactly where it is authored. * Styles will be global and not scoped to the component. <style is:inline> /* inline: relative & npm package imports are not supported. */ @import '/assets/some-public-styles.css'; span { color: green; }</style><script is:inline> /* inline: relative & npm package imports are not supported. */ console.log('I am inlined right here in the final output HTML.');</script> `define:vars={...}` can pass server-side variables from your component frontmatter into the client `<script>` or `<style>` tags. Any JSON-serializable frontmatter variable is supported, including `props` passed to your component through `Astro.props`. Values are serialized with `JSON.stringify()`. ---const foregroundColor = "rgb(221 243 228)";const backgroundColor = "rgb(24 121 78)";const message = "Astro is awesome!";---<style define:vars={{ textColor: foregroundColor, backgroundColor }}> h1 { background-color: var(--backgroundColor); color: var(--textColor); }</style><script define:vars={{ message }}> alert(message);</script> ## Advanced Directives Section titled Advanced Directives `is:raw` instructs the Astro compiler to treat any children of that element as text. This means that all special Astro templating syntax will be ignored inside of this component. For example, if you had a custom Katex component that converted some text to HTML, you could have users do this: ---import Katex from '../components/Katex.astro';---<Katex is:raw>Some conflicting {syntax} here</Katex> --- ## Page: https://docs.astro.build/en/reference/configuration-reference/ The following reference covers all supported configuration options in Astro. To learn more about configuring Astro, read our guide on Configuring Astro. import { defineConfig } from 'astro/config'export default defineConfig({ // your configuration options here...}) ## Top-Level Options Section titled Top-Level Options **Type:** `string` Your final, deployed URL. Astro uses this full URL to generate your sitemap and canonical URLs in your final build. It is strongly recommended that you set this configuration to get the most out of Astro. { site: 'https://www.my-site.dev'} **Type:** `string` The base path to deploy to. Astro will use this path as the root for your pages and assets both in development and in production build. In the example below, `astro dev` will start your server at `/docs`. { base: '/docs'} When using this option, all of your static asset imports and URLs should add the base as a prefix. You can access this value via `import.meta.env.BASE_URL`. The value of `import.meta.env.BASE_URL` will be determined by your `trailingSlash` config, no matter what value you have set for `base`. A trailing slash is always included if `trailingSlash: "always"` is set. If `trailingSlash: "never"` is set, `BASE_URL` will not include a trailing slash, even if `base` includes one. Additionally, Astro will internally manipulate the configured value of `config.base` before making it available to integrations. The value of `config.base` as read by integrations will also be determined by your `trailingSlash` configuration in the same way. In the example below, the values of `import.meta.env.BASE_URL` and `config.base` when processed will both be `/docs`: { base: '/docs/', trailingSlash: "never"} In the example below, the values of `import.meta.env.BASE_URL` and `config.base` when processed will both be `/docs/`: { base: '/docs', trailingSlash: "always"} **Type:** `'always' | 'never' | 'ignore'` **Default:** `'ignore'` Set the route matching behavior for trailing slashes in the dev server and on-demand rendered pages. Choose from the following options: * `'ignore'` - Match URLs regardless of whether a trailing ”/” exists. Requests for “/about” and “/about/” will both match the same route. * `'always'` - Only match URLs that include a trailing slash (e.g: “/about/”). In production, requests for on-demand rendered URLs without a trailing slash will be redirected to the correct URL for your convenience. However, in development, they will display a warning page reminding you that you have `always` configured. * `'never'` - Only match URLs that do not include a trailing slash (e.g: “/about”). In production, requests for on-demand rendered URLs with a trailing slash will be redirected to the correct URL for your convenience. However, in development, they will display a warning page reminding you that you have `never` configured. When redirects occur in production for GET requests, the redirect will be a 301 (permanent) redirect. For all other request methods, it will be a 308 (permanent, and preserve the request method) redirect. Trailing slashes on prerendered pages are handled by the hosting platform, and may not respect your chosen configuration. See your hosting platform’s documentation for more information. You cannot use Astro redirects for this use case at this point. { // Example: Require a trailing slash during development trailingSlash: 'always'} **See Also:** * build.format **Type:** `Record<string, RedirectConfig>` **Default:** `{}` **Added in:** `astro@2.9.0` Specify a mapping of redirects where the key is the route to match and the value is the path to redirect to. You can redirect both static and dynamic routes, but only to the same kind of route. For example, you cannot have a `'/article': '/blog/[...slug]'` redirect. export default defineConfig({ redirects: { '/old': '/new', '/blog/[...slug]': '/articles/[...slug]', '/about': 'https://example.com/about', '/news': { status: 302, destination: 'https://example.com/news' }, // '/product1/', '/product1' // Note, this is not supported }}) For statically-generated sites with no adapter installed, this will produce a client redirect using a `<meta http-equiv="refresh">` tag and does not support status codes. When using SSR or with a static adapter in `output: static` mode, status codes are supported. Astro will serve redirected GET requests with a status of `301` and use a status of `308` for any other request method. You can customize the redirection status code using an object in the redirect config: export default defineConfig({ redirects: { '/other': { status: 302, destination: '/place', }, }}) **Type:** `'static' | 'server'` **Default:** `'static'` Specifies the output target for builds. * `'static'` - Prerender all your pages by default, outputting a completely static site if none of your pages opt out of prerendering. * `'server'` - Use server-side rendering (SSR) for all pages by default, always outputting a server-rendered site. import { defineConfig } from 'astro/config';export default defineConfig({ output: 'static'}) **See Also:** * adapter **Type:** `AstroIntegration` Deploy to your favorite server, serverless, or edge host with build adapters. Import one of our first-party adapters for Netlify, Vercel, and more to engage Astro SSR. See our On-demand Rendering guide for more on SSR, and our deployment guides for a complete list of hosts. import netlify from '@astrojs/netlify';{ // Example: Build for Netlify serverless deployment adapter: netlify(),} **See Also:** * output **Type:** `AstroIntegration[]` Extend Astro with custom integrations. Integrations are your one-stop-shop for adding framework support (like Solid.js), new features (like sitemaps), and new libraries (like Partytown). Read our Integrations Guide for help getting started with Astro Integrations. import react from '@astrojs/react';import mdx from '@astrojs/mdx';{ // Example: Add React + MDX support to Astro integrations: [react(), mdx()]} **Type:** `string` **CLI:** `--root` **Default:** `"."` (current working directory) You should only provide this option if you run the `astro` CLI commands in a directory other than the project root directory. Usually, this option is provided via the CLI instead of the Astro config file, since Astro needs to know your project root before it can locate your config file. If you provide a relative path (ex: `--root: './my-project'`) Astro will resolve it against your current working directory. { root: './my-project-directory'} $ astro build --root ./my-project-directory **Type:** `string` **Default:** `"./src"` Set the directory that Astro will read your site from. The value can be either an absolute file system path or a path relative to the project root. { srcDir: './www'} **Type:** `string` **Default:** `"./public"` Set the directory for your static assets. Files in this directory are served at `/` during dev and copied to your build directory during build. These files are always served or copied as-is, without transform or bundling. The value can be either an absolute file system path or a path relative to the project root. { publicDir: './my-custom-publicDir-directory'} **Type:** `string` **Default:** `"./dist"` Set the directory that `astro build` writes your final build to. The value can be either an absolute file system path or a path relative to the project root. { outDir: './my-custom-build-directory'} **See Also:** * build.server **Type:** `string` **Default:** `"./node_modules/.astro"` Set the directory for caching build artifacts. Files in this directory will be used in subsequent builds to speed up the build time. The value can be either an absolute file system path or a path relative to the project root. { cacheDir: './my-custom-cache-directory'} **Type:** `boolean` **Default:** `true` This is an option to minify your HTML output and reduce the size of your HTML files. By default, Astro removes whitespace from your HTML, including line breaks, from `.astro` components in a lossless manner. Some whitespace may be kept as needed to preserve the visual rendering of your HTML. This occurs both in development mode and in the final build. To disable HTML compression, set `compressHTML` to false. { compressHTML: false} ### scopedStyleStrategy Section titled scopedStyleStrategy **Type:** `'where' | 'class' | 'attribute'` **Default:** `'attribute'` **Added in:** `astro@2.4` Specify the strategy used for scoping styles within Astro components. Choose from: * `'where'` - Use `:where` selectors, causing no specificity increase. * `'class'` - Use class-based selectors, causing a +1 specificity increase. * `'attribute'` - Use `data-` attributes, causing a +1 specificity increase. Using `'class'` is helpful when you want to ensure that element selectors within an Astro component override global style defaults (e.g. from a global stylesheet). Using `'where'` gives you more control over specificity, but requires that you use higher-specificity selectors, layers, and other tools to control which selectors are applied. Using `'attribute'` is useful when you are manipulating the `class` attribute of elements and need to avoid conflicts between your own styling logic and Astro’s application of styles. **Type:** `Record<"checkOrigin", boolean> | undefined` **Default:** `{checkOrigin: true}` **Added in:** `astro@4.9.0` Enables security measures for an Astro website. These features only exist for pages rendered on demand (SSR) using `server` mode or pages that opt out of prerendering in `static` mode. By default, Astro will automatically check that the “origin” header matches the URL sent by each request in on-demand rendered pages. You can disable this behavior by setting `checkOrigin` to `false`: export default defineConfig({ output: "server", security: { checkOrigin: false }}) #### security.checkOrigin Section titled security.checkOrigin **Type:** `boolean` **Default:** `true` **Added in:** `astro@4.9.0` Performs a check that the “origin” header, automatically passed by all modern browsers, matches the URL sent by each `Request`. This is used to provide Cross-Site Request Forgery (CSRF) protection. The “origin” check is executed only for pages rendered on demand, and only for the requests `POST`, `PATCH`, `DELETE` and `PUT` with one of the following `content-type` headers: `'application/x-www-form-urlencoded'`, `'multipart/form-data'`, `'text/plain'`. If the “origin” header doesn’t match the `pathname` of the request, Astro will return a 403 status code and will not render the page. **Type:** `SessionConfig` **Added in:** `astro@5.3.0` Configures experimental session support by specifying a storage `driver` as well as any associated `options`. You must enable the `experimental.session` flag to use this feature. Some adapters may provide a default session driver, but you can override it with your own configuration. You can specify any driver from Unstorage or provide a custom config which will override your adapter’s default. See the experimental session guide for more information. { session: { // Required: the name of the Unstorage driver driver: 'redis', // The required options depend on the driver options: { url: process.env.REDIS_URL, }, } } **Type:** `ViteUserConfig` Pass additional configuration options to Vite. Useful when Astro doesn’t support some advanced configuration that you may need. View the full `vite` configuration object documentation on vite.dev. { vite: { ssr: { // Example: Force a broken package to skip SSR processing, if needed external: ['broken-npm-package'], } }} { vite: { // Example: Add custom vite plugins directly to your Astro project plugins: [myPlugin()], }} **Type:** `('file' | 'directory' | 'preserve')` **Default:** `'directory'` Control the output file format of each page. This value may be set by an adapter for you. * `'file'`: Astro will generate an HTML file named for each page route. (e.g. `src/pages/about.astro` and `src/pages/about/index.astro` both build the file `/about.html`) * `'directory'`: Astro will generate a directory with a nested `index.html` file for each page. (e.g. `src/pages/about.astro` and `src/pages/about/index.astro` both build the file `/about/index.html`) * `'preserve'`: Astro will generate HTML files exactly as they appear in your source folder. (e.g. `src/pages/about.astro` builds `/about.html` and `src/pages/about/index.astro` builds the file `/about/index.html`) { build: { // Example: Generate `page.html` instead of `page/index.html` during build. format: 'file' }} #### Effect on Astro.url Section titled Effect on Astro.url Setting `build.format` controls what `Astro.url` is set to during the build. When it is: * `directory` - The `Astro.url.pathname` will include a trailing slash to mimic folder behavior. (e.g. `/foo/`) * `file` - The `Astro.url.pathname` will include `.html`. (e.g. `/foo.html`) This means that when you create relative URLs using `new URL('./relative', Astro.url)`, you will get consistent behavior between dev and build. To prevent inconsistencies with trailing slash behaviour in dev, you can restrict the `trailingSlash` option to `'always'` or `'never'` depending on your build format: * `directory` - Set `trailingSlash: 'always'` * `file` - Set `trailingSlash: 'never'` **Type:** `string` **Default:** `'./client'` Controls the output directory of your client-side CSS and JavaScript when building a website with server-rendered pages. `outDir` controls where the code is built to. This value is relative to the `outDir`. { output: 'server', build: { client: './client' }} **Type:** `string` **Default:** `'./server'` Controls the output directory of server JavaScript when building to SSR. This value is relative to the `outDir`. { build: { server: './server' }} **Type:** `string` **Default:** `'_astro'` **Added in:** `astro@2.0.0` Specifies the directory in the build output where Astro-generated assets (bundled JS and CSS for example) should live. { build: { assets: '_custom' }} **See Also:** * outDir ### build.assetsPrefix Section titled build.assetsPrefix **Type:** `string | Record<string, string>` **Default:** `undefined` **Added in:** `astro@2.2.0` Specifies the prefix for Astro-generated asset links. This can be used if assets are served from a different domain than the current site. This requires uploading the assets in your local `./dist/_astro` folder to a corresponding `/_astro/` folder on the remote domain. To rename the `_astro` path, specify a new directory in `build.assets`. To fetch all assets uploaded to the same domain (e.g. `https://cdn.example.com/_astro/...`), set `assetsPrefix` to the root domain as a string (regardless of your `base` configuration): { build: { assetsPrefix: 'https://cdn.example.com' }} **Added in:** `astro@4.5.0` You can also pass an object to `assetsPrefix` to specify a different domain for each file type. In this case, a `fallback` property is required and will be used by default for any other files. { build: { assetsPrefix: { 'js': 'https://js.cdn.example.com', 'mjs': 'https://js.cdn.example.com', 'css': 'https://css.cdn.example.com', 'fallback': 'https://cdn.example.com' } }} ### build.serverEntry Section titled build.serverEntry **Type:** `string` **Default:** `'entry.mjs'` Specifies the file name of the server entrypoint when building to SSR. This entrypoint is usually dependent on which host you are deploying to and will be set by your adapter for you. Note that it is recommended that this file ends with `.mjs` so that the runtime detects that the file is a JavaScript module. { build: { serverEntry: 'main.mjs' }} ### build.redirects Section titled build.redirects **Type:** `boolean` **Default:** `true` **Added in:** `astro@2.6.0` Specifies whether redirects will be output to HTML during the build. This option only applies to `output: 'static'` mode; in SSR redirects are treated the same as all responses. This option is mostly meant to be used by adapters that have special configuration files for redirects and do not need/want HTML based redirects. { build: { redirects: false }} ### build.inlineStylesheets Section titled build.inlineStylesheets **Type:** `'always' | 'auto' | 'never'` **Default:** `auto` **Added in:** `astro@2.6.0` Control whether project styles are sent to the browser in a separate css file or inlined into `<style>` tags. Choose from the following options: * `'always'` - project styles are inlined into `<style>` tags * `'auto'` - only stylesheets smaller than `ViteConfig.build.assetsInlineLimit` (default: 4kb) are inlined. Otherwise, project styles are sent in external stylesheets. * `'never'` - project styles are sent in external stylesheets { build: { inlineStylesheets: `never`, },} ### build.concurrency Section titled build.concurrency **Type:** `number` **Default:** `1` **Added in:** `astro@4.16.0` The number of pages to build in parallel. **In most cases, you should not change the default value of `1`.** Use this option only when other attempts to reduce the overall rendering time (e.g. batch or cache long running tasks like fetch calls or data access) are not possible or are insufficient. If the number is set too high, page rendering may slow down due to insufficient memory resources and because JS is single-threaded. { build: { concurrency: 2 }} Customize the Astro dev server, used by both `astro dev` and `astro preview`. { server: { port: 1234, host: true}} To set different configuration based on the command run (“dev”, “preview”) a function can also be passed to this configuration option. { // Example: Use the function syntax to customize based on command server: ({ command }) => ({ port: command === 'dev' ? 4321 : 4000 })} **Type:** `string | boolean` **Default:** `false` **Added in:** `astro@0.24.0` Set which network IP addresses the server should listen on (i.e. non-localhost IPs). * `false` - do not expose on a network IP address * `true` - listen on all addresses, including LAN and public addresses * `[custom-address]` - expose on a network IP address at `[custom-address]` (ex: `192.168.0.1`) **Type:** `number` **Default:** `4321` Set which port the server should listen on. If the given port is already in use, Astro will automatically try the next available port. { server: { port: 8080 }} **Type:** `string | boolean` **Default:** `false` **Added in:** `astro@4.1.0` Controls whether the dev server should open in your browser window on startup. Pass a full URL string (e.g. “http://example.com”) or a pathname (e.g. “/about”) to specify the URL to open. { server: { open: "/about" }} **Type:** `OutgoingHttpHeaders` **Default:** `{}` **Added in:** `astro@1.7.0` Set custom HTTP response headers to be sent in `astro dev` and `astro preview`. ## Dev Toolbar Options Section titled Dev Toolbar Options ### devToolbar.enabled Section titled devToolbar.enabled **Type:** `boolean` **Default:** `true` Whether to enable the Astro Dev Toolbar. This toolbar allows you to inspect your page islands, see helpful audits on performance and accessibility, and more. This option is scoped to the entire project, to only disable the toolbar for yourself, run `npm run astro preferences disable devToolbar`. To disable the toolbar for all your Astro projects, run `npm run astro preferences disable devToolbar --global`. ## Prefetch Options Section titled Prefetch Options **Type:** `boolean | object` Enable prefetching for links on your site to provide faster page transitions. (Enabled by default on pages using the `<ClientRouter />` router. Set `prefetch: false` to opt out of this behaviour.) This configuration automatically adds a prefetch script to every page in the project giving you access to the `data-astro-prefetch` attribute. Add this attribute to any `<a />` link on your page to enable prefetching for that page. <a href="/about" data-astro-prefetch>About</a> Further customize the default prefetching behavior using the `prefetch.defaultStrategy` and `prefetch.prefetchAll` options. See the Prefetch guide for more information. ### prefetch.prefetchAll Section titled prefetch.prefetchAll **Type:** `boolean` Enable prefetching for all links, including those without the `data-astro-prefetch` attribute. This value defaults to `true` when using the `<ClientRouter />` router. Otherwise, the default value is `false`. prefetch: { prefetchAll: true} When set to `true`, you can disable prefetching individually by setting `data-astro-prefetch="false"` on any individual links. <a href="/about" data-astro-prefetch="false">About</a> ### prefetch.defaultStrategy Section titled prefetch.defaultStrategy **Type:** `'tap' | 'hover' | 'viewport' | 'load'` **Default:** `'hover'` The default prefetch strategy to use when the `data-astro-prefetch` attribute is set on a link with no value. * `'tap'`: Prefetch just before you click on the link. * `'hover'`: Prefetch when you hover over or focus on the link. (default) * `'viewport'`: Prefetch as the links enter the viewport. * `'load'`: Prefetch all links on the page after the page is loaded. You can override this default value and select a different strategy for any individual link by setting a value on the attribute. <a href="/about" data-astro-prefetch="viewport">About</a> **Type:** `Object` **Default:** `{route: '/_image', entrypoint: undefined}` **Added in:** `astro@3.1.0` Set the endpoint to use for image optimization in dev and SSR. The `entrypoint` property can be set to `undefined` to use the default image endpoint. { image: { // Example: Use a custom image endpoint at `/custom_endpoint` endpoint: { route: '/custom_endpoint', entrypoint: 'src/my_endpoint.ts', }, },} **Type:** `Object` **Default:** `{entrypoint: 'astro/assets/services/sharp', config?: {}}` **Added in:** `astro@2.1.0` Set which image service is used for Astro’s assets support. The value should be an object with an entrypoint for the image service to use and optionally, a config object to pass to the service. The service entrypoint can be either one of the included services, or a third-party package. { image: { // Example: Enable the Sharp-based image service with a custom config service: { entrypoint: 'astro/assets/services/sharp', config: { limitInputPixels: false, }, }, },} #### image.service.config.limitInputPixels Section titled image.service.config.limitInputPixels **Type:** `number | boolean` **Default:** `true` **Added in:** `astro@4.1.0` Whether or not to limit the size of images that the Sharp image service will process. Set `false` to bypass the default image size limit for the Sharp image service and process large images. **Type:** `Array<string>` **Default:** `[]` **Added in:** `astro@2.10.10` Defines a list of permitted image source domains for remote image optimization. No other remote images will be optimized by Astro. This option requires an array of individual domain names as strings. Wildcards are not permitted. Instead, use `image.remotePatterns` to define a list of allowed source URL patterns. { image: { // Example: Allow remote image optimization from a single domain domains: ['astro.build'], },} ### image.remotePatterns Section titled image.remotePatterns **Type:** `Array<RemotePattern>` **Default:** `[]` **Added in:** `astro@2.10.10` Defines a list of permitted image source URL patterns for remote image optimization. `remotePatterns` can be configured with four properties: 1. protocol 2. hostname 3. port 4. pathname { image: { // Example: allow processing all images from your aws s3 bucket remotePatterns: [{ protocol: 'https', hostname: '**.amazonaws.com', }], },} You can use wildcards to define the permitted `hostname` and `pathname` values as described below. Otherwise, only the exact values provided will be configured: `hostname`: * Start with ’\*\*.’ to allow all subdomains (‘endsWith’). * Start with ’\*.’ to allow only one level of subdomain. `pathname`: * End with ’/\*\*’ to allow all sub-routes (‘startsWith’). * End with ’/\*’ to allow only one level of sub-route. ### image.experimentalLayout Section titled image.experimentalLayout **Type:** `ImageLayout` **Default:** `undefined` The default layout type for responsive images. Can be overridden by the `layout` prop on the image component. Requires the `experimental.responsiveImages` flag to be enabled. * `responsive` - The image will scale to fit the container, maintaining its aspect ratio, but will not exceed the specified dimensions. * `fixed` - The image will maintain its original dimensions. * `full-width` - The image will scale to fit the container, maintaining its aspect ratio. ### image.experimentalObjectFit Section titled image.experimentalObjectFit **Type:** `ImageFit` **Default:** `"cover"` The default object-fit value for responsive images. Can be overridden by the `fit` prop on the image component. Requires the `experimental.responsiveImages` flag to be enabled. ### image.experimentalObjectPosition Section titled image.experimentalObjectPosition **Type:** `string` **Default:** `"center"` The default object-position value for responsive images. Can be overridden by the `position` prop on the image component. Requires the `experimental.responsiveImages` flag to be enabled. ### image.experimentalBreakpoints Section titled image.experimentalBreakpoints **Type:** `Array<number>` **Default:** `[640, 750, 828, 1080, 1280, 1668, 2048, 2560] | [640, 750, 828, 960, 1080, 1280, 1668, 1920, 2048, 2560, 3200, 3840, 4480, 5120, 6016]` The breakpoints used to generate responsive images. Requires the `experimental.responsiveImages` flag to be enabled. The full list is not normally used, but is filtered according to the source and output size. The defaults used depend on whether a local or remote image service is used. For remote services the more comprehensive list is used, because only the required sizes are generated. For local services, the list is shorter to reduce the number of images generated. ## Markdown Options Section titled Markdown Options ### markdown.shikiConfig Section titled markdown.shikiConfig **Type:** `Partial<ShikiConfig>` Shiki is our default syntax highlighter. You can configure all options via the `markdown.shikiConfig` object: import { defineConfig } from 'astro/config';export default defineConfig({ markdown: { shikiConfig: { // Choose from Shiki's built-in themes (or add your own) // https://shiki.style/themes theme: 'dracula', // Alternatively, provide multiple themes // See note below for using dual light/dark themes themes: { light: 'github-light', dark: 'github-dark', }, // Disable the default colors // https://shiki.style/guide/dual-themes#without-default-color // (Added in v4.12.0) defaultColor: false, // Add custom languages // Note: Shiki has countless langs built-in, including .astro! // https://shiki.style/languages langs: [], // Add custom aliases for languages // Map an alias to a Shiki language ID: https://shiki.style/languages#bundled-languages // https://shiki.style/guide/load-lang#custom-language-aliases langAlias: { cjs: "javascript" }, // Enable word wrap to prevent horizontal scrolling wrap: true, // Add custom transformers: https://shiki.style/guide/transformers // Find common transformers: https://shiki.style/packages/transformers transformers: [], }, },}); See the code syntax highlighting guide for usage and examples. ### markdown.syntaxHighlight Section titled markdown.syntaxHighlight **Type:** `SyntaxHighlightConfig | SyntaxHighlightConfigType | false` **Default:** `{ type: 'shiki', excludeLangs: ['math'] }` Which syntax highlighter to use for Markdown code blocks (\`\`\`), if any. This determines the CSS classes that Astro will apply to your Markdown code blocks. * `shiki` - use the Shiki highlighter (`github-dark` theme configured by default) * `prism` - use the Prism highlighter and provide your own Prism stylesheet * `false` - do not apply syntax highlighting. { markdown: { // Example: Switch to use prism for syntax highlighting in Markdown syntaxHighlight: 'prism', }} For more control over syntax highlighting, you can instead specify a configuration object with the properties listed below. #### markdown.syntaxHighlight.type Section titled markdown.syntaxHighlight.type **Type:** `'shiki' | 'prism'` **Default:** `'shiki'` **Added in:** `astro@5.5.0` The default CSS classes to apply to Markdown code blocks. (If no other syntax highlighting configuration is needed, you can instead set `markdown.syntaxHighlight` directly to `shiki`, `prism`, or `false`.) #### markdown.syntaxHighlight.excludeLangs Section titled markdown.syntaxHighlight.excludeLangs **Type:** `Array<string>` **Default:** `['math']` **Added in:** `astro@5.5.0` An array of languages to exclude from the default syntax highlighting specified in `markdown.syntaxHighlight.type`. This can be useful when using tools that create diagrams from Markdown code blocks, such as Mermaid.js and D2. import { defineConfig } from 'astro/config';export default defineConfig({ markdown: { syntaxHighlight: { type: 'shiki', excludeLangs: ['mermaid', 'math'], }, },}); **Type:** `RemarkPlugins` Pass remark plugins to customize how your Markdown is built. You can import and apply the plugin function (recommended), or pass the plugin name as a string. import remarkToc from 'remark-toc';{ markdown: { remarkPlugins: [ [remarkToc, { heading: "contents"} ] ] }} ### markdown.rehypePlugins Section titled markdown.rehypePlugins **Type:** `RehypePlugins` Pass rehype plugins to customize how your Markdown’s output HTML is processed. You can import and apply the plugin function (recommended), or pass the plugin name as a string. import { rehypeAccessibleEmojis } from 'rehype-accessible-emojis';{ markdown: { rehypePlugins: [rehypeAccessibleEmojis] }} **Type:** `boolean` **Default:** `true` **Added in:** `astro@2.0.0` Astro uses GitHub-flavored Markdown by default. To disable this, set the `gfm` flag to `false`: { markdown: { gfm: false, }} ### markdown.smartypants Section titled markdown.smartypants **Type:** `boolean` **Default:** `true` **Added in:** `astro@2.0.0` Astro uses the SmartyPants formatter by default. To disable this, set the `smartypants` flag to `false`: { markdown: { smartypants: false, }} **Type:** `RemarkRehype` Pass options to remark-rehype. { markdown: { // Example: Translate the footnotes text to another language, here are the default English values remarkRehype: { footnoteLabel: "Footnotes", footnoteBackLabel: "Back to reference 1"}, },}; **Type:** `object` **Added in:** `astro@3.5.0` Configures i18n routing and allows you to specify some customization options. See our guide for more information on internationalization in Astro **Type:** `Locales` **Added in:** `astro@3.5.0` A list of all locales supported by the website. This is a required field. Languages can be listed either as individual codes (e.g. `['en', 'es', 'pt-br']`) or mapped to a shared `path` of codes (e.g. `{ path: "english", codes: ["en", "en-US"]}`). These codes will be used to determine the URL structure of your deployed site. No particular language code format or syntax is enforced, but your project folders containing your content files must match exactly the `locales` items in the list. In the case of multiple `codes` pointing to a custom URL path prefix, store your content files in a folder with the same name as the `path` configured. ### i18n.defaultLocale Section titled i18n.defaultLocale **Type:** `string` **Added in:** `astro@3.5.0` The default locale of your website/application, that is one of the specified `locales`. This is a required field. No particular language format or syntax is enforced, but we suggest using lower-case and hyphens as needed (e.g. “es”, “pt-br”) for greatest compatibility. **Type:** `Record<string, string>` **Added in:** `astro@3.5.0` The fallback strategy when navigating to pages that do not exist (e.g. a translated page has not been created). Use this object to declare a fallback `locale` route for each language you support. If no fallback is specified, then unavailable pages will return a 404. The following example configures your content fallback strategy to redirect unavailable pages in `/pt-br/` to their `es` version, and unavailable pages in `/fr/` to their `en` version. Unavailable `/es/` pages will return a 404. export default defineConfig({ i18n: { defaultLocale: "en", locales: ["en", "fr", "pt-br", "es"], fallback: { pt: "es", fr: "en" } }}) **Type:** `object | "manual"` **Default:** `object` **Added in:** `astro@3.7.0` Controls the routing strategy to determine your site URLs. Set this based on your folder/URL path configuration for your default language. export default defineConfig({ i18n: { defaultLocale: "en", locales: ["en", "fr"], routing: { prefixDefaultLocale: false, redirectToDefaultLocale: true, fallbackType: "redirect", } }}) Since 4.6.0, this option can also be set to `manual`. When this routing strategy is enabled, Astro will **disable** its i18n middleware and no other `routing` options (e.g. `prefixDefaultLocale`) may be configured. You will be responsible for writing your own routing logic, or executing Astro’s i18n middleware manually alongside your own. export default defineConfig({ i18n: { defaultLocale: "en", locales: ["en", "fr"], routing: "manual" }}) #### i18n.routing.prefixDefaultLocale Section titled i18n.routing.prefixDefaultLocale **Type:** `boolean` **Default:** `false` **Added in:** `astro@3.7.0` When `false`, only non-default languages will display a language prefix. The `defaultLocale` will not show a language prefix and content files do not exist in a localized folder. URLs will be of the form `example.com/[locale]/content/` for all non-default languages, but `example.com/content/` for the default locale. When `true`, all URLs will display a language prefix. URLs will be of the form `example.com/[locale]/content/` for every route, including the default language. Localized folders are used for every language, including the default. export default defineConfig({ i18n: { defaultLocale: "en", locales: ["en", "fr", "pt-br", "es"], routing: { prefixDefaultLocale: true, } }}) #### i18n.routing.redirectToDefaultLocale Section titled i18n.routing.redirectToDefaultLocale **Type:** `boolean` **Default:** `true` **Added in:** `astro@4.2.0` Configures whether or not the home URL (`/`) generated by `src/pages/index.astro` will redirect to `/[defaultLocale]` when `prefixDefaultLocale: true` is set. Set `redirectToDefaultLocale: false` to disable this automatic redirection at the root of your site: export default defineConfig({ i18n:{ defaultLocale: "en", locales: ["en", "fr"], routing: { prefixDefaultLocale: true, redirectToDefaultLocale: false } }}) #### i18n.routing.fallbackType Section titled i18n.routing.fallbackType **Type:** `"redirect" | "rewrite"` **Default:** `"redirect"` **Added in:** `astro@4.15.0` When `i18n.fallback` is configured to avoid showing a 404 page for missing page routes, this option controls whether to redirect to the fallback page, or to rewrite the fallback page’s content in place. By default, Astro’s i18n routing creates pages that redirect your visitors to a new destination based on your fallback configuration. The browser will refresh and show the destination address in the URL bar. When `i18n.routing.fallback: "rewrite"` is configured, Astro will create pages that render the contents of the fallback page on the original, requested URL. With the following configuration, if you have the file `src/pages/en/about.astro` but not `src/pages/fr/about.astro`, the `astro build` command will generate `dist/fr/about.html` with the same content as the `dist/en/about.html` page. Your site visitor will see the English version of the page at `https://example.com/fr/about/` and will not be redirected. export default defineConfig({ i18n: { defaultLocale: "en", locales: ["en", "fr"], routing: { prefixDefaultLocale: false, fallbackType: "rewrite", }, fallback: { fr: "en", } },}) **Type:** `Record<string, string>` **Default:** `{}` **Added in:** `astro@4.3.0` Configures the URL pattern of one or more supported languages to use a custom domain (or sub-domain). When a locale is mapped to a domain, a `/[locale]/` path prefix will not be used. However, localized folders within `src/pages/` are still required, including for your configured `defaultLocale`. Any other locale not configured will default to a localized path-based URL according to your `prefixDefaultLocale` strategy (e.g. `https://example.com/[locale]/blog`). export default defineConfig({ site: "https://example.com", output: "server", // required, with no prerendered pages adapter: node({ mode: 'standalone', }), i18n: { defaultLocale: "en", locales: ["en", "fr", "pt-br", "es"], prefixDefaultLocale: false, domains: { fr: "https://fr.example.com", es: "https://example.es" } },}) Both page routes built and URLs returned by the `astro:i18n` helper functions `getAbsoluteLocaleUrl()` and `getAbsoluteLocaleUrlList()` will use the options set in `i18n.domains`. See the Internationalization Guide for more details, including the limitations of this feature. **Type:** `object` **Default:** `{}` **Added in:** `astro@5.0.0` Configuration options for type-safe environment variables. See our guide for more information on environment variables in Astro. **Type:** `EnvSchema` **Default:** `{}` **Added in:** `astro@5.0.0` An object that uses `envField` to define the data type and properties of your environment variables: `context` (client or server), `access` (public or secret), a `default` value to use, and whether or not this environment variable is `optional` (defaults to `false`). import { defineConfig, envField } from "astro/config"export default defineConfig({ env: { schema: { API_URL: envField.string({ context: "client", access: "public", optional: true }), PORT: envField.number({ context: "server", access: "public", default: 4321 }), API_SECRET: envField.string({ context: "server", access: "secret" }), } }}) `envField` supports four data types: string, number, enum, and boolean. `context` and `access` are required properties for all data types. The following shows the complete list of properties available for each data type: import { envField } from "astro/config"envField.string({ // context & access optional: true, default: "foo", max: 20, min: 1, length: 13, url: true, includes: "oo", startsWith: "f", endsWith: "o",})envField.number({ // context & access optional: true, default: 15, gt: 2, min: 1, lt: 3, max: 4, int: true,})envField.boolean({ // context & access optional: true, default: true,})envField.enum({ // context & access values: ['foo', 'bar', 'baz'], // required optional: true, default: 'baz',}) ### env.validateSecrets Section titled env.validateSecrets **Type:** `boolean` **Default:** `false` **Added in:** `astro@5.0.0` Whether or not to validate secrets on the server when starting the dev server or running a build. By default, only public variables are validated on the server when starting the dev server or a build, and private variables are validated at runtime only. If enabled, private variables will also be checked on start. This is useful in some continuous integration (CI) pipelines to make sure all your secrets are correctly set before deploying. import { defineConfig, envField } from "astro/config"export default defineConfig({ env: { schema: { // ... }, validateSecrets: true }}) --- ## Page: https://docs.astro.build/en/reference/cli-reference/ You can use the Command-Line Interface (CLI) provided by Astro to develop, build, and preview your project from a terminal window. Use the CLI by running one of the **commands** documented on this page with your preferred package manager, optionally followed by any **flags**. Flags customize the behavior of a command. One of the commands you’ll use most often is `astro dev`. This command starts the development server and gives you a live, updating preview of your site in a browser as you work: * npm * pnpm * Yarn # start the development servernpx astro dev You can type `astro --help` in your terminal to display a list of all available commands: * npm * pnpm * Yarn npx astro --help The following message will display in your terminal: astro [command] [...flags]Commands add Add an integration. build Build your project and write it to disk. check Check your project for errors. create-key Create a cryptography key dev Start the development server. docs Open documentation in your web browser. info List info about your current Astro setup. preview Preview your build locally. sync Generate TypeScript types for all Astro modules. preferences Configure user preferences. telemetry Configure telemetry settings.Global Flags --config <path> Specify your config file. --root <path> Specify your project root folder. --site <url> Specify your project site.--base <pathname> Specify your project base. --verbose Enable verbose logging. --silent Disable all logging. --version Show the version number and exit. --help Show this help message. You can add the `--help` flag after any command to get a list of all the flags for that command. * npm * pnpm * Yarn # get a list of all flags for the `dev` commandnpm run dev -- --help The following message will display in your terminal: astro dev [...flags]Flags --port Specify which port to run on. Defaults to 4321. --host Listen on all addresses, including LAN and public addresses.--host <custom-address> Expose on a network IP address at <custom-address> --open Automatically open the app in the browser on server start --force Clear the content layer cache, forcing a full rebuild. --help (-h) See all available flags. ### `package.json` scripts Section titled package.json scripts You can also use scripts in `package.json` for shorter versions of these commands. Using a script allows you to use the same commands that you may be familiar with from other projects, such as `npm run build`. The following scripts for the most common `astro` commands (`astro dev`, `astro build`, and `astro preview`) are added for you automatically when you create a project using the `create astro` wizard. When you follow the instructions to install Astro manually, you are instructed to add these scripts yourself. You can also add more scripts to this list manually for any commands you use frequently. { "scripts": { "dev": "astro dev", "build": "astro build", "preview": "astro preview" }} You will often use these `astro` commands, or the scripts that run them, without any flags. Add flags to the command when you want to customize the command’s behavior. For example, you may wish to start the development server on a different port, or build your site with verbose logs for debugging. * npm * pnpm * Yarn # run the dev server on port 8080 using the `dev` script in `package.json`npm run dev -- --port 8080# build your site with verbose logs using the `build` script in `package.json`npm run build -- --verbose Runs Astro’s development server. This is a local HTTP server that doesn’t bundle assets. It uses Hot Module Replacement (HMR) to update your browser as you save changes in your editor. Builds your site for deployment. By default, this will generate static files and place them in a `dist/` directory. If any routes are rendered on demand, this will generate the necessary server files to serve your site. The command accepts common flags and the following additional flags: **Added in:** `astro@5.0.0` Outputs a development-based build similar to code transformed in `astro dev`. This can be useful to test build-only issues with additional debugging information included. Starts a local server to serve the contents of your static directory (`dist/` by default) created by running `astro build`. This command allows you to preview your site locally after building to catch any errors in your build output before deploying it. It is not designed to be run in production. For help with production hosting, check out our guide on Deploying an Astro Website. Since Astro 1.5.0, the Node adapter supports `astro preview` for builds generated with on-demand rendering. Can be combined with the common flags documented below. Runs diagnostics (such as type-checking within `.astro` files) against your project and reports errors to the console. If any errors are found the process will exit with a code of **1**. This command is intended to be used in CI workflows. ### Flags Use these flags to customize the behavior of the command. The command will watch for any changes in your project, and will report any errors. Specifies a different root directory to check. Uses the current working directory by default. #### `--tsconfig <path-to-file>` Section titled --tsconfig <path-to-file> Specifies a `tsconfig.json` file to use manually. If not provided, Astro will attempt to find a config, or infer the project’s config automatically. #### `--minimumFailingSeverity <error|warning|hint>` Section titled --minimumFailingSeverity <error|warning|hint> Specifies the minimum severity needed to exit with an error code. Defaults to `error`. For example, running `astro check --minimumFailingSeverity warning` will cause the command to exit with an error if any warnings are detected. #### `--minimumSeverity <error|warning|hint>` Section titled --minimumSeverity <error|warning|hint> Specifies the minimum severity to output. Defaults to `hint`. For example, running `astro check --minimumSeverity warning` will show errors and warning, but not hints. #### `--preserveWatchOutput` Section titled --preserveWatchOutput Specifies not to clear the output between checks when in watch mode. Specifies not to run `astro sync` before checking the project. **Added in:** `astro@2.0.0` Generates TypeScript types for all Astro modules. This sets up a `.astro/types.d.ts` file for type inferencing, and defines modules for features that rely on generated types: * The `astro:content` module for the Content Collections API. * The `astro:db` module for Astro DB. * The `astro:env` module for Astro Env. * The `astro:actions` module for Astro Actions Adds an integration to your configuration. Read more in the integrations guide. Launches the Astro Docs website directly from the terminal. Reports useful information about your current Astro environment. Useful for providing information when opening an issue. astro info Example output: Astro v3.0.12Node v20.5.1System macOS (arm64)Package Manager pnpmOutput serverAdapter @astrojs/vercel/serverlessIntegrations none ## `astro preferences` Section titled astro preferences Manage user preferences with the `astro preferences` command. User preferences are specific to individual Astro users, unlike the `astro.config.mjs` file which changes behavior for everyone working on a project. User preferences are scoped to the current project by default, stored in a local `.astro/settings.json` file. Using the `--global` flag, user preferences can also be applied to every Astro project on the current machine. Global user preferences are stored in an operating system-specific location. ### Available preferences * `devToolbar` — Enable or disable the development toolbar in the browser. (Default: `true`) * `checkUpdates` — Enable or disable automatic update checks for the Astro CLI. (Default: `true`) The `list` command prints the current settings of all configurable user preferences. It also supports a machine-readable `--json` output. astro preferences list Example terminal output: | Preference | Value | | --- | --- | | devToolbar.enabled | true | | checkUpdates.enabled | true | You can `enable`, `disable`, or `reset` preferences to their default. For example, to disable the devToolbar in a specific Astro project: astro preferences disable devToolbar To disable the devToolbar in all Astro projects on the current machine: astro preferences disable --global devToolbar The devToolbar can later be enabled with: astro preferences enable devToolbar The `reset` command resets a preference to its default value: astro preferences reset devToolbar ## `astro telemetry` Section titled astro telemetry Sets telemetry configuration for the current CLI user. Telemetry is anonymous data that provides the Astro team insights into which Astro features are most often used. For more information see Astro’s telemetry page. Telemetry can be disabled with this CLI command: astro telemetry disable Telemetry can later be re-enabled with: astro telemetry enable The `reset` command resets the telemetry data: astro telemetry reset Specifies the path to the project root. If not specified, the current working directory is assumed to be the root. The root is used for finding the Astro configuration file. astro --root myRootFolder/myProjectFolder dev Specifies the path to the config file relative to the project root. Defaults to `astro.config.mjs`. Use this if you use a different name for your configuration file or have your config file in another folder. astro --config config/astro.config.mjs dev **Added in:** `astro@5.0.0` Clear the content layer cache, forcing a full rebuild. **Added in:** `astro@5.0.0` Configures the `mode` inline config for your project. **Added in:** `astro@3.3.0` Configures the `outDir` for your project. Passing this flag will override the `outDir` value in your `astro.config.mjs` file, if one exists. Configures the `site` for your project. Passing this flag will override the `site` value in your `astro.config.mjs` file, if one exists. **Added in:** `astro@1.4.1` Configures the `base` for your project. Passing this flag will override the `base` value in your `astro.config.mjs` file, if one exists. Specifies which port to run the dev server and preview server on. Defaults to `4321`. ### `--host [optional host address]` Section titled --host \[optional host address\] Sets which network IP addresses the dev server and preview server should listen on (i.e. non-localhost IPs). This can be useful for testing your project on local devices like a mobile phone during development. * `--host` — listen on all addresses, including LAN and public addresses * `--host <custom-address>` — expose on a network IP address at `<custom-address>` ### `--allowed-hosts` Section titled --allowed-hosts **Added in:** `astro@5.4.0` Specifies the hostnames that Astro is allowed to respond to in `dev` or `preview` modes. Can be passed a comma-separated list of hostnames or `true` to allow any hostname. Refer to Vite’s `allowedHosts` feature for more information, including security implications of allowing hostnames. Enables verbose logging, which is helpful when debugging an issue. Enables silent logging, which will run the server without any console output. Automatically opens the app in the browser on server start. Can be passed a full URL string (e.g. `--open http://example.com`) or a pathname (e.g. `--open /about`) to specify the URL to open. Use these flags to get information about the `astro` CLI. Prints the Astro version number and exits. Prints the help message and exits. --- ## Page: https://docs.astro.build/en/reference/routing-reference/ There is no separate routing configuration in Astro. Every supported page file located within the special `src/pages/` directory creates a route. When the file name contains a parameter, a route can create multiple pages dynamically, otherwise it creates a single page. By default, all Astro page routes and endpoints are generated and prerendered at build time. On-demand server rendering can be set for individual routes, or as the default. **Type:** `boolean` **Default:** `true` in static mode (default); `false` with `output: 'server'` configuration **Added in:** `astro@1.0.0` A value exported from each individual route to determine whether or not it is prerendered. By default, all pages and endpoints are prerendered and will be statically generated at build time. You can opt out of prerendering on one or more routes, and you can have both static and on-demand rendered routes in the same project. ### Per-page override Section titled Per-page override You can override the default value to enable on demand rendering for an individual route by exporting `prerender` with the value `false` from that file: ---export const prerender = false---<!-- server-rendered content --><!-- the rest of my site is static --> ### Switch to `server` mode Section titled Switch to server mode You can override the default value for all routes by configuring `output: 'server'`. In this output mode, all pages and endpoints will be generated on the server upon request by default instead of being prerendered. In `server` mode, enable prerendering for an individual route by exporting `prerender` with the value `true` from that file: ---// with `output: 'server'` configuredexport const prerender = true---<!-- My static about page --><!-- All other pages are rendered on demand --> **Type:** `boolean` **Default:** `false` **Added in:** `astro@3.4.0` A value exported from an individual route to determine whether or not it should be rendered as a full HTML page. By default, all files located within the reserved `src/pages/` directory automatically include the `<!DOCTYPE html>` declaration and additional `<head>` content such as Astro’s scoped styles and scripts. You can override the default value to designate the content as a page partial for an individual route by exporting a value for `partial` from that file: ---export const partial = true---<!-- Generated HTML available at a URL --><!-- Available to a rendering library --> The `export const partial` must be identifiable statically. It can have the value of: * The boolean **`true`**. * An environment variable using import.meta.env such as `import.meta.env.USE_PARTIALS`. ## `getStaticPaths()` Section titled getStaticPaths() **Type:** `(options: GetStaticPathsOptions) => Promise<GetStaticPathsResult> | GetStaticPathsResult` **Added in:** `astro@1.0.0` A function to generate multiple, prerendered page routes from a single `.astro` page component with one or more parameters in its file path. Use this for routes that will be created at build time, also known as static site building. The `getStaticPaths()` function must return an array of objects to determine which URL paths will be prerendered by Astro. Each object must include a `params` object, to specify route paths. The object may optionally contain a `props` object with data to be passed to each page template. ---// In 'server' mode, opt in to prerendering:// export const prerender = trueexport async function getStaticPaths() { return [ // { params: { /* required */ }, props: { /* optional */ } }, { params: { post: '1' } }, // [post] is the parameter { params: { post: '2' } }, // must match the file name // ... ];}---<!-- Your HTML template here. --> `getStaticPaths()` can also be used in static file endpoints for dynamic routing. The `params` key of each object in the array returned by `getStaticPaths()` tells Astro what routes to build. The keys in `params` must match the parameters defined in your component file path. The value for each `params` object must match the parameters used in the page name. `params` are encoded into the URL, so only strings are supported as values. For example,`src/pages/posts/[id].astro`has an `id` parameter in its file name. The following `getStaticPaths()` function in this `.astro` component tells Astro to statically generate `posts/1`, `posts/2`, and `posts/3` at build time. ---export async function getStaticPaths() { return [ { params: { id: '1' } }, { params: { id: '2' } }, { params: { id: '3' } } ];}const { id } = Astro.params;---<h1>{id}</h1> ### Data passing with `props` Section titled Data passing with props To pass additional data to each generated page, you can set a `props` value on each object in the array returned by `getStaticPaths()`. Unlike `params`, `props` are not encoded into the URL and so aren’t limited to only strings. For example, if you generate pages with data fetched from a remote API, you can pass the full data object to the page component inside of `getStaticPaths()`. The page template can reference the data from each post using `Astro.props`. ---export async function getStaticPaths() { const response = await fetch('...'); const data = await response.json(); return data.map((post) => { return { params: { id: post.id }, props: { post }, }; });}const { id } = Astro.params;const { post } = Astro.props;---<h1>{id}: {post.name}</h1> **Added in:** `astro@1.0.0` A function that can be returned from `getStaticPaths()` to divide a collection of content items into separate pages. `paginate()` will automatically generate the necessary array to return from `getStaticPaths()` to create one URL for every page of your paginated collection. The page number will be passed as a `param`, and the page data will be passed as a `page` prop. The following example fetches and passes 150 items to the `paginate` function, and creates static, prerendered pages at build time that will display 10 items per page: ---export async function getStaticPaths({ paginate }) { // Load your data with fetch(), getCollection(), etc. const response = await fetch(`https://pokeapi.co/api/v2/pokemon?limit=150`); const result = await response.json(); const allPokemon = result.results; // Return a paginated collection of paths for all items return paginate(allPokemon, { pageSize: 10 });}const { page } = Astro.props;--- `paginate()` has the following arguments: * `data` - array containing the page’s data passed to the `paginate()` function * `options` - Optional object with the following properties: * `pageSize` - The number of items shown per page (`10` by default) * `params` - Send additional parameters for creating dynamic routes * `props` - Send additional props to be available on each page `paginate()` assumes a file name of `[page].astro` or `[...page].astro`. The `page` param becomes the page number in your URL: * `/posts/[page].astro` would generate the URLs `/posts/1`, `/posts/2`, `/posts/3`, etc. * `/posts/[...page].astro` would generate the URLs `/posts`, `/posts/2`, `/posts/3`, etc. **Type:** `Page<TData>` Pagination will pass a `page` prop to every rendered page that represents a single page of data in the paginated collection. This includes the data that you’ve paginated (`page.data`) as well as metadata for the page (`page.url`, `page.start`, `page.end`, `page.total`, etc). This metadata is useful for things like a “Next Page” button or a “Showing 1-10 of 100” message. **Type:** `Array<TData>` Array of data returned from the `paginate()` function for the current page. **Type:** `number` Index of the first item on the current page, starting at `0`. (e.g. if `pageSize: 25`, this would be `0` on page 1, `25` on page 2, etc.) **Type:** `number` Index of the last item on the current page. **Type:** `number` **Default:** `10` The total number of items per page. **Type:** `number` The total number of items across all pages. ##### `page.currentPage` Section titled page.currentPage **Type:** `number` The current page number, starting with `1`. **Type:** `number` The total number of pages. ##### `page.url.current` Section titled page.url.current **Type:** `string` Get the URL of the current page (useful for canonical URLs). If a value is set for `base`, the URL starts with that value. **Type:** `string | undefined` Get the URL of the previous page (will be `undefined` if on page 1). If a value is set for `base`, prepend the base path to the URL. **Type:** `string | undefined` Get the URL of the next page (will be `undefined` if no more pages). If a value is set for `base`, prepend the base path to the URL. **Type:** `string | undefined` **Added in:** `astro@4.12.0` Get the URL of the first page (will be `undefined` if on page 1). If a value is set for `base`, prepend the base path to the URL. **Type:** `string | undefined` **Added in:** `astro@4.12.0` Get the URL of the last page (will be `undefined` if no more pages). If a value is set for `base`, prepend the base path to the URL. --- ## Page: https://docs.astro.build/en/reference/api-reference/ When rendering a page, Astro provides a runtime API specific to the current render. This includes useful information such as the current page URL as well as APIs to perform actions like redirecting to another page. In `.astro` components, this context is available from the `Astro` global object. Endpoint functions are also called with this same context object as their first argument, whose properties mirror the Astro global properties. Some properties are only available for routes rendered on demand or may have limited functionality on prerendered pages. The `Astro` global object is available to all `.astro` files. Use the `context` object in endpoint functions to serve static or live server endpoints and in middleware to inject behavior when a page or endpoint is about to be rendered. ## The context object Section titled The context object The following properties are available on the `Astro` global (e.g. `Astro.props`, `Astro.redirect()`) and are also available on the context object (e.g. `context.props`, `context.redirect()`) passed to endpoint functions and middleware. `props` is an object containing any values that have been passed as component attributes. ---const { title, date } = Astro.props;---<div> <h1>{title}</h1> <p>{date}</p></div> ---import Heading from '../components/Heading.astro';---<Heading title="My First Post" date="09 Aug 2022" /> The `props` object also contains any `props` passed from `getStaticPaths()` when rendering static routes. * Astro.props * context.props ---export function getStaticPaths() { return [ { params: { id: '1' }, props: { author: 'Blu' } }, { params: { id: '2' }, props: { author: 'Erika' } }, { params: { id: '3' }, props: { author: 'Matthew' } } ];}const { id } = Astro.params;const { author } = Astro.props;--- See also: Data Passing with `props` `params` is an object containing the values of dynamic route segments matched for a request. Its keys must match the parameters in the page or endpoint file path. In static builds, this will be the `params` returned by `getStaticPaths()` used for prerendering dynamic routes: * Astro.params * context.params ---export function getStaticPaths() { return [ { params: { id: '1' } }, { params: { id: '2' } }, { params: { id: '3' } } ];}const { id } = Astro.params;---<h1>{id}</h1> When routes are rendered on demand, `params` can be any value matching the path segments in the dynamic route pattern. ---import { getPost } from '../api';const post = await getPost(Astro.params.id);// No posts found with this IDif (!post) { return Astro.redirect("/404")}---<html> <h1>{post.name}</h1></html> See also: `params` **Type:** `URL` **Added in:** `astro@1.0.0` `url` is a URL object constructed from the current `request.url` value. It is useful for interacting with individual properties of the request URL, like pathname and origin. `Astro.url` is equivalent to doing `new URL(Astro.request.url)`. `url` will be a `localhost` URL in dev mode. When building a site, prerendered routes will receive a URL based on the `site` and `base` options. If `site` is not configured, prerendered pages will receive a `localhost` URL during builds as well. <h1>The current URL is: {Astro.url}</h1><h1>The current URL pathname is: {Astro.url.pathname}</h1><h1>The current URL origin is: {Astro.url.origin}</h1> You can also use `url` to create new URLs by passing it as an argument to `new URL()`. ---// Example: Construct a canonical URL using your production domainconst canonicalURL = new URL(Astro.url.pathname, Astro.site);// Example: Construct a URL for SEO meta tags using your current domainconst socialImageURL = new URL('/images/preview.png', Astro.url);---<link rel="canonical" href={canonicalURL} /><meta property="og:image" content={socialImageURL} /> **Type:** `URL | undefined` `site` returns a `URL` made from `site` in your Astro config. It returns `undefined` if you have not set a value for `site` in your Astro config. <link rel="alternate" type="application/rss+xml" title="Your Site's Title" href={new URL("rss.xml", Astro.site)}/> **Type:** `string` **Added in:** `astro@1.0.0` `clientAddress` specifies the IP address of the request. This property is only available for routes rendered on demand and cannot be used on prerendered pages. * Astro.clientAddress * context.clientAddress ---export const prerender = false; // Not needed in 'server' mode---<div>Your IP address is: <span class="address">{Astro.clientAddress}</span></div> **Type**: `boolean` **Added in:** `astro@5.0.0` A boolean representing whether or not the current page is prerendered. You can use this property to run conditional logic in middleware, for example, to avoid accessing headers in prerendered pages. **Type:** `string` **Added in:** `astro@1.0.0` `generator` provides the current version of Astro your project is running. This is a convenient way to add a `<meta name="generator">` tag with your current version of Astro. It follows the format `"Astro v5.x.x"`. * Astro.generator * context.generator <html> <head> <meta name="generator" content={Astro.generator} /> </head> <body> <footer> <p>Built with <a href="https://astro.build">{Astro.generator}</a></p> </footer> </body></html> **Type:** `Request` `request` is a standard Request object. It can be used to get the `url`, `headers`, `method`, and even the body of the request. * Astro.request * context.request <p>Received a {Astro.request.method} request to "{Astro.request.url}".</p><p>Received request headers:</p><p><code>{JSON.stringify(Object.fromEntries(Astro.request.headers))}</code></p> **Type:** `ResponseInit & { readonly headers: Headers }` `response` is a standard `ResponseInit` object. It has the following structure. * `status`: The numeric status code of the response, e.g., `200`. * `statusText`: The status message associated with the status code, e.g., `'OK'`. * `headers`: A `Headers` instance that you can use to set the HTTP headers of the response. `Astro.response` is used to set the `status`, `statusText`, and `headers` for a page’s response. ---if (condition) { Astro.response.status = 404; Astro.response.statusText = 'Not found';}--- Or to set a header: ---Astro.response.headers.set('Set-Cookie', 'a=b; Path=/;');--- **Type:** `(path: string, status?: number) => Response` **Added in:** `astro@1.5.0` `redirect()` returns a Response object that allows you to redirect to another page, and optionally provide an HTTP response status code as a second parameter. A page (and not a child component) must `return` the result of `Astro.redirect()` for the redirect to occur. For statically-generated routes, this will produce a client redirect using a `<meta http-equiv="refresh">` tag and does not support status codes. For on-demand rendered routes, setting a custom status code is supported when redirecting. If not specified, redirects will be served with a `302` status code. The following example redirects a user to a login page: * Astro.redirect() * context.redirect() ---import { isLoggedIn } from '../utils';const cookie = Astro.request.headers.get('cookie');// If the user is not logged in, redirect them to the login pageif (!isLoggedIn(cookie)) { return Astro.redirect('/login');}---<p>User information</p> **Type:** `(rewritePayload: string | URL | Request) => Promise<Response>` **Added in:** `astro@4.13.0` `rewrite()` allows you to serve content from a different URL or path without redirecting the browser to a new page. The method accepts either a string, a `URL`, or a `Request` for the location of the path. Use a string to provide an explicit path: * Astro.rewrite() * context.rewrite() ---return Astro.rewrite("/login")--- Use a `URL` type when you need to construct the URL path for the rewrite. The following example renders a page’s parent path by creating a new URL from the relative `"../"` path: * Astro.rewrite() * context.rewrite() ---return Astro.rewrite(new URL("../", Astro.url))--- Use a `Request` type for complete control of the `Request` sent to the server for the new path. The following example sends a request to render the parent page while also providing headers: * Astro.rewrite() * context.rewrite() ---return Astro.rewrite(new Request(new URL("../", Astro.url), { headers: { "x-custom-header": JSON.stringify(Astro.locals.someValue) }}))--- **Added in:** `astro@2.4.0` `locals` is an object used to store and access arbitrary information during the lifecycle of a request. `Astro.locals` is an object containing any values from the `context.locals` object set by middleware. Use this to access data returned by middleware in your `.astro` files. Middleware functions can both read and write the values of `context.locals`: import type { MiddlewareHandler } from 'astro';export const onRequest: MiddlewareHandler = ({ locals }, next) => { if (!locals.title) { locals.title = "Default Title"; } return next();} Astro components and API endpoints can read values from `locals` when they render: * Astro.locals * context.locals ---const title = Astro.locals.title;---<h1>{title}</h1> ### `preferredLocale` Section titled preferredLocale **Type:** `string | undefined` **Added in:** `astro@3.5.0` `preferredLocale` is a computed value to find the best match between your visitor’s browser language preferences and the locales supported by your site. It is computed by checking the configured locales in your `i18n.locales` array and the locales supported by the user’s browser via the header `Accept-Language`. This value is `undefined` if no such match exists. This property is only available for routes rendered on demand and cannot be used on prerendered, static pages. ### `preferredLocaleList` Section titled preferredLocaleList **Type:** `string[] | undefined` **Added in:** `astro@3.5.0` `preferredLocaleList` represents the array of all locales that are both requested by the browser and supported by your website. This produces a list of all compatible languages between your site and your visitor. If none of the browser’s requested languages are found in your locales array, then the value is `[]`. This occurs when you do not support any of your visitor’s preferred locales. If the browser does not specify any preferred languages, then this value will be `i18n.locales`: all of your supported locales will be considered equally preferred by a visitor with no preferences. This property is only available for routes rendered on demand and cannot be used on prerendered, static pages. **Type:** `string | undefined` **Added in:** `astro@3.5.6` The locale computed from the current URL, using the syntax specified in your `locales` configuration. If the URL does not contain a `/[locale]/` prefix, then the value will default to `i18n.defaultLocale`. ### `getActionResult()` Section titled getActionResult() **Type:** `(action: TAction) => ActionReturnType<TAction> | undefined` **Added in:** `astro@4.15.0` `getActionResult()` is a function that returns the result of an Action submission. This accepts an action function as an argument (e.g. `actions.logout`) and returns a `data` or `error` object when a submission is received. Otherwise, it will return `undefined`. ---import { actions } from 'astro:actions';const result = Astro.getActionResult(actions.logout);---<form action={actions.logout}> <button type="submit">Log out</button></form>{result?.error && <p>Failed to log out. Please try again.</p>} **Added in:** `astro@4.15.0` `callAction()` is a function used to call an Action handler directly from your Astro component. This function accepts an Action function as the first argument (e.g. `actions.logout`) and any input that action receives as the second argument. It returns the result of the action as a promise. ---import { actions } from 'astro:actions';const { data, error } = await Astro.callAction(actions.logout, { userId: '123' });--- **Type**: `string` **Added in:** `astro@5.0.0` The route pattern responsible for generating the current page or route. In file-based routing, this resembles the file path in your project used to create the route. When integrations create routes for your project, `context.routePattern` is identical to the value for `injectRoute.pattern`. The value will start with a leading slash and look similar to the path of a page component relative to your `src/pages/` folder without a file extension. For example, the file `src/pages/en/blog/[slug].astro` will return `/en/blog/[slug]` for `routePattern`. Every page on your site generated by that file (e.g. `/en/blog/post-1/`, `/en/blog/post-2/`, etc.) shares the same value for `routePattern`. In the case of `index.*` routes, the route pattern will not include the word “index.” For example, `src/pages/index.astro` will return `/`. You can use this property to understand which route is rendering your component. This allows you to target or analyze similarly-generated page URLs together. For example, you can use it to conditionally render certain information, or collect metrics about which routes are slower. **Type:** `AstroCookies` **Added in:** `astro@1.4.0` `cookies` contains utilities for reading and manipulating cookies for routes rendered on demand. #### Cookie utilities Section titled Cookie utilities **Type:** `(key: string, options?: AstroCookieGetOptions) => AstroCookie | undefined` Gets the cookie as an `AstroCookie` object, which contains the `value` and utility functions for converting the cookie to non-string types. **Type:** `(key: string, options?: AstroCookieGetOptions) => boolean` Whether this cookie exists. If the cookie has been set via `Astro.cookies.set()` this will return true, otherwise, it will check cookies in the `Astro.request`. **Type:** `(key: string, value: string | object, options?: AstroCookieSetOptions) => void` Sets the cookie `key` to the given value. This will attempt to convert the cookie value to a string. Options provide ways to set cookie features, such as the `maxAge` or `httpOnly`. ##### `cookies.delete()` Section titled cookies.delete() **Type:** `(key: string, options?: AstroCookieDeleteOptions) => void` Invalidates a cookie by setting the expiration date in the past (0 in Unix time). Once a cookie is “deleted” (expired), `Astro.cookies.has()` will return `false` and `Astro.cookies.get()` will return an `AstroCookie` with a `value` of `undefined`. Options available when deleting a cookie are: `domain`, `path`, `httpOnly`, `sameSite`, and `secure`. ##### `cookies.merge()` Section titled cookies.merge() **Type:** `(cookies: AstroCookies) => void` Merges a new `AstroCookies` instance into the current instance. Any new cookies will be added to the current instance and any cookies with the same name will overwrite existing values. **Type:** `() => Iterator<string>` Gets the header values for `Set-Cookie` that will be sent out with the response. #### `AstroCookie` Type Section titled AstroCookie Type The type returned from getting a cookie via `Astro.cookies.get()`. It has the following properties: **Type:** `string` The raw string value of the cookie. **Type:** `() => Record<string, any>` Parses the cookie value via `JSON.parse()`, returning an object. Throws if the cookie value is not valid JSON. **Type:** `() => number` Parses the cookie value as a Number. Returns NaN if not a valid number. **Type:** `() => boolean` Converts the cookie value to a boolean. #### `AstroCookieGetOptions` Section titled AstroCookieGetOptions **Added in:** `astro@4.1.0` The `AstroCookieGetOption` interface allows you to specify options when you get a cookie. **Type:** `(value: string) => string` Allows customization of how a cookie is deserialized into a value. #### `AstroCookieSetOptions` Section titled AstroCookieSetOptions **Added in:** `astro@4.1.0` `AstroCookieSetOptions` is an object that can be passed to `Astro.cookies.set()` when setting a cookie to customize how the cookie is serialized. **Type:** `string` Specifies the domain. If no domain is set, most clients will interpret to apply to the current domain. **Type:** `Date` Specifies the date on which the cookie will expire. **Type:** `boolean` If true, the cookie will not be accessible client-side. **Type:** `number` Specifies a number, in seconds, for which the cookie is valid. **Type:** `string` Specifies a subpath of the domain in which the cookie is applied. **Type:** `boolean | 'lax' | 'none' | 'strict'` Specifies the value of the SameSite cookie header. **Type:** `boolean` If true, the cookie is only set on https sites. **Type:** `(value: string) => string` Allows customizing how the cookie is serialized. ### Deprecated object properties Section titled Deprecated object properties `Astro.glob()` is a way to load many local files into your static site setup. ---const posts = await Astro.glob('../pages/post/*.md'); // returns an array of posts that live at ./src/pages/post/*.md---<div>{posts.slice(0, 3).map((post) => ( <article> <h2>{post.frontmatter.title}</h2> <p>{post.frontmatter.description}</p> <a href={post.url}>Read more</a> </article>))}</div> `.glob()` only takes one parameter: a relative URL glob of which local files you’d like to import. It’s asynchronous and returns an array of the exports from matching files. `.glob()` can’t take variables or strings that interpolate them, as they aren’t statically analyzable. (See the imports guide for a workaround.) This is because `Astro.glob()` is a wrapper of Vite’s `import.meta.glob()`. Markdown files loaded with `Astro.glob()` return the following `MarkdownInstance` interface: export interface MarkdownInstance<T extends Record<string, any>> { /* Any data specified in this file's YAML/TOML frontmatter */ frontmatter: T; /* The absolute file path of this file */ file: string; /* The rendered path of this file */ url: string | undefined; /* Astro Component that renders the contents of this file */ Content: AstroComponentFactory; /** (Markdown only) Raw Markdown file content, excluding layout HTML and YAML/TOML frontmatter */ rawContent(): string; /** (Markdown only) Markdown file compiled to HTML, excluding layout HTML */ compiledContent(): string; /* Function that returns an array of the h1...h6 elements in this file */ getHeadings(): Promise<{ depth: number; slug: string; text: string }[]>; default: AstroComponentFactory;} You can optionally provide a type for the `frontmatter` variable using a TypeScript generic. ---interface Frontmatter { title: string; description?: string;}const posts = await Astro.glob<Frontmatter>('../pages/post/*.md');---<ul> {posts.map(post => <li>{post.frontmatter.title}</li>)}</ul> Astro files have the following interface: export interface AstroInstance { /* The file path of this file */ file: string; /* The URL for this file (if it is in the pages directory) */ url: string | undefined; default: AstroComponentFactory;} Other files may have various different interfaces, but `Astro.glob()` accepts a TypeScript generic if you know exactly what an unrecognized file type contains. ---interface CustomDataFile { default: Record<string, any>;}const data = await Astro.glob<CustomDataFile>('../data/**/*.js');--- --- ## Page: https://docs.astro.build/en/reference/modules/astro-actions/ **Added in:** `astro@4.15.0` Actions help you build a type-safe backend you can call from client code and HTML forms. All utilities to define and call actions are exposed by the `astro:actions` module. For examples and usage instructions, see the Actions guide. ## Imports from `astro:actions` Section titled Imports from astro:actions import { actions, defineAction, isInputError, isActionError, ActionError, } from 'astro:actions'; **Added in:** `astro@4.15.0` The `defineAction()` utility is used to define new actions from the `src/actions/index.ts` file. This accepts a `handler()` function containing the server logic to run, and an optional `input` property to validate input parameters at runtime. import { defineAction } from 'astro:actions';import { z } from 'astro:schema';export const server = { getGreeting: defineAction({ input: z.object({ name: z.string(), }), handler: async (input, context) => { return `Hello, ${input.name}!` } })} #### `handler()` property Section titled handler() property **Type:** `(input, context) => any` `defineAction()` requires a `handler()` function containing the server logic to run when the action is called. Data returned from the handler is automatically serialized and sent to the caller. The `handler()` is called with user input as its first argument. If an `input` validator is set, the user input will be validated before being passed to the handler. The second argument is a `context` object containing most of Astro’s standard endpoint context, excluding `getActionResult()`, `callAction()`, and `redirect()`. Return values are parsed using the devalue library. This supports JSON values and instances of `Date()`, `Map()`, `Set()`, and `URL()`. #### `input` validator Section titled input validator **Type:** `ZodType | undefined` The optional `input` property accepts a Zod validator (e.g. Zod object, Zod discriminated union) to validate handler inputs at runtime. If the action fails to validate, a `BAD_REQUEST` error is returned and the `handler` is not called. If `input` is omitted, the `handler` will receive an input of type `unknown` for JSON requests and type `FormData` for form requests. ##### Use with `accept: 'form'` Section titled Use with accept: 'form' If your action accepts form inputs, use the `z.object()` validator to automatically parse form data to a typed object. The following validators are supported for form data fields: * Inputs of type `number` can be validated using `z.number()` * Inputs of type `checkbox` can be validated using `z.boolean()` * Inputs of type `file` can be validated using `z.instanceof(File)` * Multiple inputs of the same `name` can be validated using `z.array(/* validator */)` * All other inputs can be validated using `z.string()` Extension functions including `.refine()`, `.transform()`, and `.pipe()` are also supported on the `z.object()` validator. To apply a union of different validators, use the `z.discriminatedUnion()` wrapper to narrow the type based on a specific form field. This example accepts a form submission to either “create” or “update” a user, using the form field with the name `type` to determine which object to validate against: import { defineAction } from 'astro:actions';import { z } from 'astro:schema';export const server = { changeUser: defineAction({ accept: 'form', input: z.discriminatedUnion('type', [ z.object({ // Matches when the `type` field has the value `create` type: z.literal('create'), name: z.string(), email: z.string().email(), }), z.object({ // Matches when the `type` field has the value `update` type: z.literal('update'), id: z.number(), name: z.string(), email: z.string().email(), }), ]), async handler(input) { if (input.type === 'create') { // input is { type: 'create', name: string, email: string } } else { // input is { type: 'update', id: number, name: string, email: string } } }, }),}; **Type:** `(error?: unknown | ActionError) => boolean` **Added in:** `astro@4.15.0` The `isInputError()` utility is used to check whether an `ActionError` is an input validation error. When the `input` validator is a `z.object()`, input errors include a `fields` object with error messages grouped by name. ### `isActionError()` Section titled isActionError() **Type:** `(error?: unknown | ActionError) => boolean` **Added in:** `astro@4.15.0` The `isActionError()` utility is used to check whether your action raised an `ActionError` within the handler property. This is useful when narrowing the type of a generic error in a `try / catch` block. **Added in:** `astro@4.15.0` The `ActionError()` constructor is used to create errors thrown by an action `handler`. This accepts a `code` property describing the error that occurred (example: `"UNAUTHORIZED"`), and an optional `message` property with further details. **Added in:** `astro@4.15.0` The `code` property accepts human-readable versions of all HTTP status codes. The following codes are supported: * `BAD_REQUEST` (400): The client sent invalid input. This error is thrown when an action `input` validator fails to validate. * `UNAUTHORIZED` (401): The client lacks valid authentication credentials. * `FORBIDDEN` (403): The client is not authorized to access a resource. * `NOT_FOUND` (404): The server cannot find the requested resource. * `METHOD_NOT_SUPPORTED` (405): The server does not support the requested method. * `TIMEOUT` (408): The server timed out while processing the request. * `CONFLICT` (409): The server cannot update a resource due to a conflict. * `PRECONDITION_FAILED` (412): The server does not meet a precondition of the request. * `PAYLOAD_TOO_LARGE` (413): The server cannot process the request because the payload is too large. * `UNSUPPORTED_MEDIA_TYPE` (415): The server does not support the request’s media type. Note: Actions already check the `Content-Type` header for JSON and form requests, so you likely won’t need to raise this code manually. * `UNPROCESSABLE_CONTENT` (422): The server cannot process the request due to semantic errors. * `TOO_MANY_REQUESTS` (429): The server has exceeded a specified rate limit. * `CLIENT_CLOSED_REQUEST` (499): The client closed the request before the server could respond. * `INTERNAL_SERVER_ERROR` (500): The server failed unexpectedly. * `NOT_IMPLEMENTED` (501): The server does not support the requested feature. * `BAD_GATEWAY` (502): The server received an invalid response from an upstream server. * `SERVICE_UNAVAILABLE` (503): The server is temporarily unavailable. * `GATEWAY_TIMEOUT` (504): The server received a timeout from an upstream server. **Added in:** `astro@4.15.0` The `message` property accepts a string. (e.g. “User must be logged in.“) ### `getActionContext()` Section titled getActionContext() **Type:** `(context: APIContext) => ActionMiddlewareContext` **Added in:** `astro@5.0.0` `getActionContext()` is a function called from your middleware handler to retrieve information about inbound action requests. This function returns an `action` object with information about the request, and the `setActionResult()` and `serializeActionResult()` functions to programmatically set the value returned by `Astro.getActionResult()`. `getActionContext()` lets you programmatically get and set action results using middleware, allowing you to persist action results from HTML forms, gate action requests with added security checks, and more. import { defineMiddleware } from 'astro:middleware';import { getActionContext } from 'astro:actions';export const onRequest = defineMiddleware(async (context, next) => { const { action, setActionResult, serializeActionResult } = getActionContext(context); if (action?.calledFrom === 'form') { const result = await action.handler(); setActionResult(action.name, serializeActionResult(result)); } return next();}); **Type:** `{ calledFrom: 'rpc' | 'form', name: string, handler: () => Promise<SafeResult<any, any>> } | undefined` `action` is an object containing information about an inbound action request. It is available from `getActionContext()`, and provides the action name, handler, and whether the action was called from an client-side RPC function (e.g. `actions.newsletter()`) or an HTML form action. import { defineMiddleware } from 'astro:middleware';import { getActionContext } from 'astro:actions';export const onRequest = defineMiddleware(async (context, next) => { const { action, setActionResult, serializeActionResult } = getActionContext(context); if (action?.calledFrom === 'rpc' && action.name.startsWith('private')) { // Check for a valid session token } // ...}); #### `setActionResult()` Section titled setActionResult() **Type:** `(actionName: string, actionResult: SerializedActionResult) => void` `setActionResult()` is a function to programmatically set the value returned by `Astro.getActionResult()` in middleware. It is passed the action name and an action result serialized by `serializeActionResult()`. This is useful when calling actions from an HTML form to persist and load results from a session. import { defineMiddleware } from 'astro:middleware';import { getActionContext } from 'astro:actions';export const onRequest = defineMiddleware(async (context, next) => { const { action, setActionResult, serializeActionResult } = getActionContext(context); if (action?.calledFrom === 'form') { const result = await action.handler(); // ... handle the action result setActionResult(action.name, serializeActionResult(result)); } return next();}); #### `serializeActionResult()` Section titled serializeActionResult() **Type:** `(result: SafeResult<any, any>) => SerializedActionResult` `serializeActionResult()` will serialize an action result to JSON for persistence. This is required to properly handle non-JSON return values like `Map` or `Date` as well as the `ActionError` object. Call this function when serializing an action result to be passed to `setActionResult()`: import { defineMiddleware } from 'astro:middleware';import { getActionContext } from 'astro:actions';export const onRequest = defineMiddleware(async (context, next) => { const { action, setActionResult, serializeActionResult } = getActionContext(context); if (action) { const result = await action.handler(); setActionResult(action.name, serializeActionResult(result)); } // ...}); #### `deserializeActionResult()` Section titled deserializeActionResult() **Type:** `(result: SerializedActionResult) => SafeResult<any, any>` `deserializeActionResult()` will reverse the effect of `serializeActionResult()` and return an action result to its original state. This is useful to access the `data` and `error` objects on a serialized action result. ### `getActionPath()` Section titled getActionPath() **Type:** `(action: ActionClient<any, any, any>) => string` **Added in:** `astro@5.1.0` The `getActionPath()` utility accepts an action and returns a URL path so you can execute an action call as a `fetch()` operation directly. This allows you to provide details such as custom headers when you call your action. Then, you can handle the custom-formatted returned data as needed, just as if you had called an action directly. This example shows how to call a defined `like` action passing the `Authorization` header and the `keepalive` option: <script>import { actions, getActionPath } from 'astro:actions'await fetch(getActionPath(actions.like), { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer YOUR_TOKEN' }, body: JSON.stringify({ id: 'YOUR_ID' }), keepalive: true})</script> This example shows how to call the same `like` action using the `sendBeacon` API: <script>import { actions, getActionPath } from 'astro:actions'navigator.sendBeacon( getActionPath(actions.like), new Blob([JSON.stringify({ id: 'YOUR_ID' })], { type: 'application/json' }))</script> --- ## Page: https://docs.astro.build/en/reference/modules/astro-assets/ **Added in:** `astro@3.0.0` 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` Section titled Imports from astro:assets import { Image, Picture, getImage, inferRemoteSize, } from 'astro:assets'; ---// import the Image component and the imageimport { Image } from 'astro:assets';import myImage from "../assets/my_image.png"; // Image is 1600x900---<!-- `alt` is mandatory on the Image component --><Image src={myImage} alt="A description of my image." /> <!-- Output --><!-- Image is optimized, proper attributes are enforced --><img src="/_astro/my_image.hash.webp" width="1600" height="900" decoding="async" loading="lazy" alt="A description of my image."/> #### Image properties Section titled Image properties The `<Image />` component accepts all properties accepted by the HTML `<img>` tag in addition to the properties described below. **Type:** `ImageMetadata | string | Promise<{ default: ImageMetadata }>` The format of the `src` value of your image file depends on where your image file is located: * **Local images in `src/`** - you must **also import the image** using a relative file path or configure and use an import alias. Then use the import name as the `src` value: ---import { Image } from 'astro:assets';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"/> **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/`) Section titled width and height (required for images in public/) **Type:** `number | undefined` These properties define the dimensions to use for the image. 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. **Type:** ``(number | `${number}x`)[] | undefined`` **Added in:** `astro@3.3.0` A list of pixel densities to generate for the image. 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. ---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."/> <!-- 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"/> **Type:** `number[] | undefined` **Added in:** `astro@3.3.0` 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. 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. ---import { Image } from 'astro:assets';import myImage from '../assets/my_image.png'; // Image is 1600x900---<Image src={myImage} widths={[240, 540, 720, myImage.width]} sizes={`(max-width: 360px) 240px, (max-width: 720px) 540px, (max-width: 1600px) 720px, ${myImage.width}px`} alt="A description of my image."/> <!-- Output --><img src="/_astro/my_image.hash.webp" srcset=" /_astro/my_image.hash.webp 240w, /_astro/my_image.hash.webp 540w, /_astro/my_image.hash.webp 720w, /_astro/my_image.hash.webp 1600w " sizes=" (max-width: 360px) 240px, (max-width: 720px) 540px, (max-width: 1600px) 720px, 1600px " alt="A description of my image." width="1600" height="900" loading="lazy" decoding="async"/> **Type:** `ImageOutputFormat | undefined` You can optionally state the image file type output to be used. By default, the `<Image />` component will produce a `.webp` file. **Type:** `ImageQuality | undefined` `quality` is an optional property that can either be: * a preset (`low`, `mid`, `high`, `max`) that is automatically normalized between formats. * a number from `0` to `100` (interpreted differently between formats). **Type:** `boolean` **Added in:** `astro@4.4.0` Allows you to set the original `width` and `height` of a remote image automatically. By default, this value is set to `false` and you must manually specify both dimensions for your remote image. Add `inferSize` to the `<Image />` component (or `inferSize: true` to `getImage()`) to infer these values from the image content when fetched. This is helpful if you don’t know the dimensions of the remote image, or if they might change: ---import { Image } from 'astro:assets';---<Image src="https://example.com/cat.png" inferSize alt="A cat sleeping in the sun." /> `inferSize` can fetch the dimensions of a remote image from a domain that has not been authorized, however the image itself will remain unprocessed. **Added in:** `astro@3.3.0` Use the built-in `<Picture />` Astro component to display a responsive image with multiple formats and/or sizes. ---import { Picture } from 'astro:assets';import myImage from "../assets/my_image.png"; // Image is 1600x900---<!-- `alt` is mandatory on the Picture component --><Picture src={myImage} formats={['avif', 'webp']} alt="A description of my image." /> <!-- Output --><picture> <source srcset="/_astro/my_image.hash.avif" type="image/avif" /> <source srcset="/_astro/my_image.hash.webp" type="image/webp" /> <img src="/_astro/my_image.hash.png" width="1600" height="900" decoding="async" loading="lazy" alt="A description of my image." /></picture> #### Picture properties Section titled Picture properties `<Picture />` accepts all the properties of the `<Image />` component, plus the following: **Type:** `ImageOutputFormat[]` An array of image formats to use for the `<source>` tags. Entries will be added as `<source>` elements in the order they are listed, and this order determines which format is displayed. For the best performance, list the most modern format first (e.g. `webp` or `avif`). By default, this is set to `['webp']`. **Type:** `ImageOutputFormat` Format to use as a fallback value for the `<img>` tag. Defaults to `.png` for static images (or `.jpg` if the image is a JPG), `.gif` for animated images, and `.svg` for SVG files. ##### `pictureAttributes` Section titled pictureAttributes **Type:** `HTMLAttributes<'picture'>` An object of attributes to be added to the `<picture>` tag. Use this property to apply attributes to the outer `<picture>` element itself. Attributes applied to the `<Picture />` component directly will apply to the inner `<img>` element, except for those used for image transformation. ---import { Picture } from "astro:assets";import myImage from "../my_image.png"; // Image is 1600x900---<Picture src={myImage} alt="A description of my image." pictureAttributes={{ style: "background-color: red;" }}/> <!-- Output --><picture style="background-color: red;"> <source srcset="/_astro/my_image.hash.webp" type="image/webp" /> <img src="/_astro/my_image.hash.png" alt="A description of my image." width="1600" height="900" loading="lazy" decoding="async" /></picture> **Type:** `(options: UnresolvedImageTransform) => Promise<GetImageResult>` 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. `getImage()` takes an options object with the same properties as the Image component (except `alt`). ---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});`}></div> It returns an object with the following type: type GetImageResult = { /* Additional HTML attributes needed to render the image (width, height, style, etc..) */ attributes: Record<string, any>; /* Validated parameters passed */ options: ImageTransform; /* Original parameters passed */ rawOptions: ImageTransform; /* Path to the generated image */ src: string; srcSet: { /* Generated values for srcset, every entry has a url and a size descriptor */ values: SrcSetValue[]; /* A value ready to use in`srcset` attribute */ attribute: string; };} ### inferRemoteSize() Section titled inferRemoteSize() **Type:** `(url: string) => Promise<Omit<ImageMetadata, 'src' | 'fsPath'>>` **Added in:** `astro@4.12.0` A function to infer the dimensions of remote images. This can be used as an alternative to passing the `inferSize` property. import { inferRemoteSize } from 'astro:assets';const {width, height} = await inferRemoteSize("https://example.com/cat.png"); --- ## Page: https://docs.astro.build/en/reference/modules/astro-content/ **Added in:** `astro@2.0.0` Content collections offer APIs to configure and query your Markdown or MDX documents in `src/content/`. For features and usage examples, see our content collections guide. ## Imports from `astro:content` Section titled Imports from astro:content import { z, defineCollection, getCollection, getEntry, getEntries, reference, render } from 'astro:content'; ### `defineCollection()` Section titled defineCollection() **Type:** `(input: CollectionConfig) => CollectionConfig` **Added in:** `astro@2.0.0` `defineCollection()` is a utility to configure a collection in a `src/content.config.*` file. 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(), }),});// Expose your defined collection to Astro// with the `collections` exportexport const collections = { blog }; This function accepts the following properties: **Type:** `() => Promise<Array<{ id: string, [key: string]: any }> | Record<string, Record<string, any>>> | Loader` **Added in:** `astro@5.0.0` A `loader` is either an object or a function that allows you to load data from any source, local or remote, into content collections. See the `Content Collection` guide for example usage. **Type:** `ZodType | (context: SchemaContext) => ZodType` **Added in:** `astro@2.0.0` `schema` is an optional Zod object to configure the type and shape of document frontmatter for a collection. Each value must use a Zod validator. See the `Content Collection` guide for example usage. **Type:** `(collection: string) => ZodEffects<ZodString, { collection, id: string }>` **Added in:** `astro@2.5.0` The `reference()` function is used in the content config to define a relationship, or “reference,” from one collection to another. This accepts a collection name and validates the entry identifier(s) specified in your content frontmatter or data file before transforming the reference into an object containing the collection name and the reference id. This example defines references from a blog author to the `authors` collection and an array of related posts to the same `blog` collection: import { defineCollection, reference, z } from 'astro:content';import { glob, file } from 'astro/loaders';const blog = defineCollection({ loader: glob({ pattern: '**/*.md', base: './src/data/blog' }), schema: z.object({ // Reference a single author from the `authors` collection by `id` author: reference('authors'), // Reference an array of related posts from the `blog` collection by `slug` relatedPosts: z.array(reference('blog')), })});const authors = defineCollection({ loader: file("src/data/authors.json"), schema: z.object({ /* ... */ })});export const collections = { blog, authors }; See the `Content Collection` guide for example usage. ### `getCollection()` Section titled getCollection() **Type:** `(collection: string, filter?: (entry: CollectionEntry<collection>) => boolean) => CollectionEntry<collection>[]` **Added in:** `astro@2.0.0` `getCollection()` is a function that retrieves a list of content collection entries by collection name. It returns all items in the collection by default, and accepts an optional `filter` function to narrow by entry properties. This allows you to query for only some items in a collection based on `id` or frontmatter values via the `data` object. ---import { getCollection } from 'astro:content';// Get all `src/content/blog/` entriesconst allBlogPosts = await getCollection('blog');// Only return posts with `draft: true` in the frontmatterconst draftBlogPosts = await getCollection('blog', ({ data }) => { return data.draft === true;});--- See the `Content Collection` guide for example usage. **Types:** * `(collection: string, id: string) => Promise<CollectionEntry<collection> | undefined>` * `({ collection: string, id: string }) => Promise<CollectionEntry<collection> | undefined>` **Added in:** `astro@2.5.0` `getEntry()` is a function that retrieves a single collection entry by collection name and the entry `id`. `getEntry()` can also be used to get referenced entries to access the `data` or `body` properties: ---import { getEntry } from 'astro:content';// Get `src/content/blog/enterprise.md`const enterprisePost = await getEntry('blog', 'enterprise');// Get `src/content/captains/picard.json`const picardProfile = await getEntry('captains', 'picard');// Get the profile referenced by `data.captain`const enterpriseCaptainProfile = await getEntry(enterprisePost.data.captain);--- See the `Content Collections` guide for examples of querying collection entries. **Type:** `(Array<{ collection: string, id: string }>) => Array<CollectionEntry<collection>>` **Added in:** `astro@2.5.0` `getEntries()` is a function that retrieves multiple collection entries from the same collection. This is useful for returning an array of referenced entries to access their associated `data` and `body` properties. ---import { getEntries, getEntry } from 'astro:content';const enterprisePost = await getEntry('blog', 'enterprise');// Get related posts referenced by `data.relatedPosts`const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts);--- **Type:** `(entry: CollectionEntry) => Promise<RenderedEntry>` **Added in:** `astro@5.0.0` A function to compile a given entry for rendering. This returns the following properties: * `<Content />` - A component used to render the document’s contents in an Astro file. * `headings` - A generated list of headings, mirroring Astro’s `getHeadings()` utility on Markdown and MDX imports. * `remarkPluginFrontmatter` \- The modified frontmatter object after any remark or rehype plugins have been applied. Set to type `any`. ---import { getEntry, render } from 'astro:content';const entry = await getEntry('blog', 'entry-1');if (!entry) { // Handle Error, for example: throw new Error('Could not find blog post 1');}const { Content, headings, remarkPluginFrontmatter } = await render(entry);--- See the `Content Collection` guide for example usage. ## `astro:content` types Section titled astro:content types import type { CollectionEntry, CollectionKey, ContentCollectionKey, DataCollectionKey, SchemaContext, } from 'astro:content'; ### `CollectionEntry` Section titled CollectionEntry Query functions including `getCollection()`, `getEntry()`, and `getEntries()` each return entries with the `CollectionEntry` type. This type is available as a utility from `astro:content`: import type { CollectionEntry } from 'astro:content'; `CollectionEntry` is a generic type. Use it with the name of the collection you’re querying. For example, an entry in your `blog` collection would have the type `CollectionEntry<'blog'>`. Each `CollectionEntry` is an object with the following values: **Example Type:** `'author-1' | 'author-2' | ...` A unique ID. Note that all IDs from Astro’s built-in `glob()` loader are slugified. **Example Type:** `'blog' | 'authors' | ...` The name of a collection in which entries are located. This is the name used to reference the collection in your schema, and in querying functions. **Type:** `CollectionSchema<TCollectionName>` An object of frontmatter properties inferred from your collection schema (see `defineCollection()` reference). Defaults to `any` if no schema is configured. **Type:** `string` A string containing the raw, uncompiled body of the Markdown or MDX document. **Added in:** `astro@3.1.0` A string union of all collection names defined in your `src/content.config.*` file. This type can be useful when defining a generic function wrapping the built-in `getCollection()`. import { type CollectionKey, getCollection } from 'astro:content';async function queryCollection(collection: CollectionKey) { return getCollection(collection, ({ data }) => { return data.draft !== true; });} The `context` object that `defineCollection` uses for the function shape of `schema`. This type can be useful when building reusable schemas for multiple collections. This includes the following property: * `image` - The `image()` schema helper that allows you to use local images in Content Collections import { defineCollection, z, type SchemaContext } from "astro:content";export const imageSchema = ({ image }: SchemaContext) => z.object({ image: image(), description: z.string().optional(), });const blog = defineCollection({ loader: /* ... */, schema: ({ image }) => z.object({ title: z.string(), permalink: z.string().optional(), image: imageSchema({ image }) }),}); --- ## Page: https://docs.astro.build/en/reference/modules/astro-env/ **Added in:** `astro@5.0.0` The `astro:env` API lets you configure a type-safe schema for environment variables you have set. This allows you to indicate whether they should be available on the server or the client, and define their data type and additional properties. For examples and usage instructions, see the `astro:env` guide. ## Imports from `astro:env` Section titled Imports from astro:env import { getSecret, } from 'astro:env/server'; **Added in:** `astro@5.0.0` The `getSecret()` helper function allows retrieving the raw value of an environment variable by its key. For example, you can retrieve a boolean value as a string: import { FEATURE_FLAG, // boolean getSecret} from 'astro:env/server'getSecret('FEATURE_FLAG') // string | undefined This can also be useful to get a secret not defined in your schema, for example one that depends on dynamic data from a database or API. If you need to retrieve environment variables programmatically, we recommend using `getSecret()` instead of `process.env` (or equivalent). Because its implementation is provided by your adapter, you won’t need to update all your calls if you switch adapters. It defaults to `process.env` in dev and build. Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/modules/astro-i18n/ **Added in:** `astro@3.5.0` This module provides functions to help you create URLs using your project’s configured locales. Creating routes for your project with the i18n router will depend on certain configuration values you have set that affect your page routes. When creating routes with these functions, be sure to take into account your individual settings for: * `base` * `trailingSlash` * `build.format` * `site` Also, note that the returned URLs created by these functions for your `defaultLocale` will reflect your `i18n.routing` configuration. For features and usage examples, see our i18n routing guide. ## Imports from `astro:i18n` Section titled Imports from astro:i18n import { getRelativeLocaleUrl, getAbsoluteLocaleUrl, getRelativeLocaleUrlList, getAbsoluteLocaleUrlList, getPathByLocale, getLocaleByPath, redirectToDefaultLocale, redirectToFallback, notFound, middleware, requestHasLocale, } from 'astro:i18n'; ### `getRelativeLocaleUrl()` Section titled getRelativeLocaleUrl() **Type:** `(locale: string, path?: string, options?: GetLocaleOptions) => string` Use this function to retrieve a relative path for a locale. If the locale doesn’t exist, Astro throws an error. ---import { getRelativeLocaleUrl } from 'astro:i18n';getRelativeLocaleUrl("fr");// returns /frgetRelativeLocaleUrl("fr", "");// returns /fr/getRelativeLocaleUrl("fr", "getting-started");// returns /fr/getting-startedgetRelativeLocaleUrl("fr_CA", "getting-started", { prependWith: "blog"});// returns /blog/fr-ca/getting-startedgetRelativeLocaleUrl("fr_CA", "getting-started", { prependWith: "blog", normalizeLocale: false});// returns /blog/fr_CA/getting-started--- ### `getAbsoluteLocaleUrl()` Section titled getAbsoluteLocaleUrl() **Type:** `(locale: string, path?: string, options?: GetLocaleOptions) => string` Use this function to retrieve an absolute path for a locale when \[`site`\] has a value. If \[`site`\] isn’t configured, the function returns a relative URL. If the locale doesn’t exist, Astro throws an error. ---import { getAbsoluteLocaleUrl } from 'astro:i18n';// If `site` is set to be `https://example.com`getAbsoluteLocaleUrl("fr");// returns https://example.com/frgetAbsoluteLocaleUrl("fr", "");// returns https://example.com/fr/getAbsoluteLocaleUrl("fr", "getting-started");// returns https://example.com/fr/getting-startedgetAbsoluteLocaleUrl("fr_CA", "getting-started", { prependWith: "blog"});// returns https://example.com/blog/fr-ca/getting-startedgetAbsoluteLocaleUrl("fr_CA", "getting-started", { prependWith: "blog", normalizeLocale: false});// returns https://example.com/blog/fr_CA/getting-started--- ### `getRelativeLocaleUrlList()` Section titled getRelativeLocaleUrlList() **Type:** `(path?: string, options?: GetLocaleOptions) => string[]` Use this like `getRelativeLocaleUrl` to return a list of relative paths for all the locales. ### `getAbsoluteLocaleUrlList()` Section titled getAbsoluteLocaleUrlList() **Type:** `(path?: string, options?: GetLocaleOptions) => string[]` Use this like `getAbsoluteLocaleUrl` to return a list of absolute paths for all the locales. ### `getPathByLocale()` Section titled getPathByLocale() **Type:** `(locale: string) => string` A function that returns the `path` associated to one or more `codes` when custom locale paths are configured. export default defineConfig({ i18n: { locales: ["es", "en", { path: "french", codes: ["fr", "fr-BR", "fr-CA"] }] }}) ---import { getPathByLocale } from 'astro:i18n';getPathByLocale("fr"); // returns "french"getPathByLocale("fr-CA"); // returns "french"--- ### `getLocaleByPath()` Section titled getLocaleByPath() **Type:** `(path: string) => string` A function that returns the `code` associated to a locale `path`. export default defineConfig({ i18n: { locales: ["es", "en", { path: "french", codes: ["fr", "fr-BR", "fr-CA"] }] }}) ---import { getLocaleByPath } from 'astro:i18n';getLocaleByPath("french"); // returns "fr" because that's the first code configured--- ### `redirectToDefaultLocale()` Section titled redirectToDefaultLocale() **Type:** `(context: APIContext, statusCode?: ValidRedirectStatus) => Promise<Response>` **Added in:** `astro@4.6.0` A function that returns a `Response` that redirects to the `defaultLocale` configured. It accepts an optional valid redirect status code. import { defineMiddleware } from "astro:middleware";import { redirectToDefaultLocale } from "astro:i18n";export const onRequest = defineMiddleware((context, next) => { if (context.url.pathname.startsWith("/about")) { return next(); } else { return redirectToDefaultLocale(context, 302); }}) ### `redirectToFallback()` Section titled redirectToFallback() **Type:** `(context: APIContext, response: Response) => Promise<Response>` **Added in:** `astro@4.6.0` A function that allows you to use your `i18n.fallback` configuration in your own middleware. import { defineMiddleware } from "astro:middleware";import { redirectToFallback } from "astro:i18n";export const onRequest = defineMiddleware(async (context, next) => { const response = await next(); if (response.status >= 300) { return redirectToFallback(context, response) } return response;}) **Type:** `(context: APIContext, response?: Response) => Promise<Response> | undefined` **Added in:** `astro@4.6.0` Use this function in your routing middleware to return a 404 when: * the current path isn’t a root. e.g. `/` or `/<base>` * the URL doesn’t contain a locale When a `Response` is passed, the new `Response` emitted by this function will contain the same headers of the original response. import { defineMiddleware } from "astro:middleware";import { notFound } from "astro:i18n";export const onRequest = defineMiddleware((context, next) => { const pathNotFound = notFound(context); if (pathNotFound) { return pathNotFound; } return next();}) **Type:** `(options: { prefixDefaultLocale: boolean, redirectToDefaultLocale: boolean }) => MiddlewareHandler` **Added in:** `astro@4.6.0` A function that allows you to programmatically create the Astro i18n middleware. This is useful when you still want to use the default i18n logic, but add only a few exceptions to your website. import { middleware } from "astro:i18n";import { sequence, defineMiddleware } from "astro:middleware";const customLogic = defineMiddleware(async (context, next) => { const response = await next(); // Custom logic after resolving the response. // It's possible to catch the response coming from Astro i18n middleware. return response;});export const onRequest = sequence(customLogic, middleware({ prefixDefaultLocale: true, redirectToDefaultLocale: false})) ### `requestHasLocale()` Section titled requestHasLocale() **Type:** `(context: APIContext) => boolean` **Added in:** `astro@4.6.0` Checks whether the current URL contains a configured locale. Internally, this function will use `APIContext#url.pathname`. import { defineMiddleware } from "astro:middleware";import { requestHasLocale } from "astro:i18n";export const onRequest = defineMiddleware(async (context, next) => { if (requestHasLocale(context)) { return next(); } return new Response("Not found", { status: 404 });}) --- ## Page: https://docs.astro.build/en/reference/modules/astro-middleware/ **Added in:** `astro@2.6.0` Middleware allows you to intercept requests and responses and inject behaviors dynamically every time a page or endpoint is about to be rendered. For features and usage examples, see our middleware guide. ## Imports from `astro:middleware` Section titled Imports from astro:middleware import { sequence, createContext, trySerializeLocals, defineMiddleware, } from 'astro:middleware'; ### `defineMiddleware()` Section titled defineMiddleware() You can import and use the utility function `defineMiddleware()` to take advantage of type safety: import { defineMiddleware } from "astro:middleware";// `context` and `next` are automatically typedexport const onRequest = defineMiddleware((context, next) => {}); **Type:** `(...handlers: MiddlewareHandler[]) => MiddlewareHandler` A function that accepts middleware functions as arguments, and will execute them in the order in which they are passed. import { sequence } from "astro:middleware";async function validation(_, next) {...}async function auth(_, next) {...}async function greeting(_, next) {...}export const onRequest = sequence(validation, auth, greeting); ### `createContext()` Section titled createContext() **Type:** `(context: CreateContext) => APIContext` **Added in:** `astro@2.8.0` A low-level API to create an `APIContext`to be passed to an Astro middleware `onRequest()` function. This function can be used by integrations/adapters to programmatically execute the Astro middleware. ### `trySerializeLocals()` Section titled trySerializeLocals() **Type:** `(value: unknown) => string` **Added in:** `astro@2.8.0` A low-level API that takes in any value and tries to return a serialized version (a string) of it. If the value cannot be serialized, the function will throw a runtime error. ## Middleware exports Section titled Middleware exports When defining your project’s middleware in `src/middleware.js`, export the following user-defined functions: **Type:** `(context: APIContext, next: MiddlewareNext) => Promise<Response> | Response | Promise<void> | void` A required exported function from `src/middleware.js` that will be called before rendering every page or API route. It receives two arguments: context and next(). `onRequest()` must return a `Response`: either directly, or by calling `next()`. export function onRequest (context, next) { // intercept response data from a request // optionally, transform the response // return a Response directly, or the result of calling `next()` return next();}; Your `onRequest()` function will be called with the following arguments: **Type:** `APIContext` The first argument of `onRequest()` is a context object. It mirrors many of the `Astro` global properties. **Type:** `(rewritePayload?: string | URL | Request) => Promise<Response>` The second argument of `onRequest()` is a function that calls all the subsequent middleware in the chain and returns a `Response`. For example, other middleware could modify the HTML body of a response and awaiting the result of `next()` would allow your middleware to respond to those changes. Since Astro v4.13.0, `next()` accepts an optional URL path parameter in the form of a string, `URL`, or `Request` to rewrite the current request without retriggering a new rendering phase. Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/modules/astro-transitions/ **Added in:** `astro@3.0.0` These modules provide functions to control and interact with the View Transitions API and client-side router. For features and usage examples, see our View Transitions guide. ## Imports from `astro:transitions` Section titled Imports from astro:transitions import { ClientRouter, fade, slide } from 'astro:transitions'; **Added in:** `astro@3.0.0` Opt in to using view transitions on individual pages by importing and adding the `<ClientRouter />` routing component to `<head>` on every desired page. ---import { ClientRouter } from 'astro:transitions';---<html lang="en"> <head> <title>My Homepage</title> <ClientRouter /> </head> <body> <h1>Welcome to my website!</h1> </body></html> See more about how to control the router and add transition directives to page elements and components. **Type:** `(opts: { duration?: string | number }) => TransitionDirectionalAnimations` **Added in:** `astro@3.0.0` Utility function to support customizing the duration of the built-in `fade` animation. ---import { fade } from 'astro:transitions';---<!-- Fade transition with the default duration --><div transition:animate="fade" /><!-- Fade transition with a duration of 400 milliseconds --><div transition:animate={fade({ duration: '0.4s' })} /> **Type:** `(opts: { duration?: string | number }) => TransitionDirectionalAnimations` **Added in:** `astro@3.0.0` Utility function to support customizing the duration of the built-in `slide` animation. ---import { slide } from 'astro:transitions';---<!-- Slide transition with the default duration --><div transition:animate="slide" /><!-- Slide transition with a duration of 400 milliseconds --><div transition:animate={slide({ duration: '0.4s' })} /> ## Imports from `astro:transitions/client` Section titled Imports from astro:transitions/client <script> import { navigate, supportsViewTransitions, transitionEnabledOnThisPage, getFallback, swapFunctions, } from 'astro:transitions/client';</script> **Type:** `(href: string, options?: Options) => void` **Added in:** `astro@3.2.0` A function that executes a navigation to the given `href` using the View Transitions API. This function signature is based on the `navigate` function from the browser Navigation API. Although based on the Navigation API, this function is implemented on top of the History API to allow for navigation without reloading the page. **Type:** `'auto' | 'push' | 'replace'` **Default:** `'auto'` **Added in:** `astro@3.2.0` Defines how this navigation should be added to the browser history. * `'push'`: the router will use `history.pushState` to create a new entry in the browser history. * `'replace'`: the router will use `history.replaceState` to update the URL without adding a new entry into navigation. * `'auto'` (default): the router will attempt `history.pushState`, but if the URL cannot be transitioned to, the current URL will remain with no changes to the browser history. This option follows the `history` option from the browser Navigation API but simplified for the cases that can happen on an Astro project. #### `formData` option Section titled formData option **Type:** `FormData` **Added in:** `astro@3.5.0` A `FormData` object for `POST` requests. When this option is provided, the requests to the navigation target page will be sent as a `POST` request with the form data object as the content. Submitting an HTML form with view transitions enabled will use this method instead of the default navigation with page reload. Calling this method allows triggering the same behavior programmatically. **Type:** `any` **Added in:** `astro@3.6.0` Arbitrary data to be included in the `astro:before-preparation` and `astro:before-swap` events caused by this navigation. This option mimics the `info` option from the browser Navigation API. **Type:** `any` **Added in:** `astro@3.6.0` Arbitrary data to be associated with the `NavitationHistoryEntry` object created by this navigation. This data can then be retrieved using the `history.getState` function from the History API. This option mimics the `state` option from the browser Navigation API. #### `sourceElement` option Section titled sourceElement option **Type:** `Element` **Added in:** `astro@3.6.0` The element that triggered this navigation, if any. This element will be available in the following events: * `astro:before-preparation` * `astro:before-swap` ### `supportsViewTransitions` Section titled supportsViewTransitions **Type:** `boolean` **Added in:** `astro@3.2.0` Whether or not view transitions are supported and enabled in the current browser. ### `transitionEnabledOnThisPage` Section titled transitionEnabledOnThisPage **Type:** `boolean` **Added in:** `astro@3.2.0` Whether or not the current page has view transitions enabled for client-side navigation. This can be used to make components that behave differently when they are used on pages with view transitions. **Type:** `() => 'none' | 'animate' | 'swap'` **Added in:** `astro@3.6.0` Returns the fallback strategy to use in browsers that do not support view transitions. See the guide on Fallback control for how to choose and configure the fallback behavior. **Added in:** `astro@4.15.0` An object containing the utility functions used to build Astro’s default swap function. These can be useful when building a custom swap function. `swapFunctions` provides the following methods: #### `deselectScripts()` Section titled deselectScripts() **Type:** `(newDocument: Document) => void` Marks scripts in the new document that should not be executed. Those scripts are already in the current document and are not flagged for re-execution using `data-astro-rerun`. #### `swapRootAttributes()` Section titled swapRootAttributes() **Type:** `(newDocument: Document) => void` Swaps the attributes between the document roots, like the `lang` attribute. This also includes Astro-injected internal attributes like `data-astro-transition`, which makes the transition direction available to Astro-generated CSS rules. When making a custom swap function, it is important to call this function so as not to break the view transition’s animations. #### `swapHeadElements()` Section titled swapHeadElements() **Type:** `(newDocument: Document) => void` Removes every element from the current document’s `<head>` that is not persisted to the new document. Then appends all new elements from the new document’s `<head>` to the current document’s `<head>`. **Type:** `() => () => void` Stores the element in focus on the current page and returns a function that when called, if the focused element was persisted, returns the focus to it. #### `swapBodyElement()` Section titled swapBodyElement() **Type:** `(newBody: Element, oldBody: Element) => void` Replaces the old body with the new body. Then, goes through every element in the old body that should be persisted and have a matching element in the new body and swaps the old element back in place. ## Lifecycle events Section titled Lifecycle events ### `astro:before-preparation` event Section titled astro:before-preparation event An event dispatched at the beginning of a navigation using the View Transitions router. This event happens before any request is made and any browser state is changed. This event has the attributes: * `info` * `sourceElement` * `navigationType` * `direction` * `from` * `to` * `formData` * `loader()` Read more about how to use this event on the View Transitions guide. ### `astro:after-preparation` event Section titled astro:after-preparation event An event dispatched after the next page in a navigation using View Transitions router is loaded. This event has no attributes. Read more about how to use this event on the View Transitions guide. ### `astro:before-swap` event Section titled astro:before-swap event An event dispatched after the next page is parsed, prepared, and linked into a document in preparation for the transition but before any content is swapped between the documents. This event can’t be canceled. Calling `preventDefault()` is a no-op. This event has the attributes: * `info` * `sourceElement` * `navigationType` * `direction` * `from` * `to` * `viewTransition` * `swap()` Read more about how to use this event on the View Transitions guide. ### `astro:after-swap` event Section titled astro:after-swap event An event dispatched after the contents of the page have been swapped but before the view transition ends. The history entry and scroll position have already been updated when this event is triggered. ### `astro:page-load` event Section titled astro:page-load event An event dispatched after a page completes loading, whether from a navigation using view transitions or native to the browser. When view transitions is enabled on the page, code that would normally execute on `DOMContentLoaded` should be changed to execute on this event. ### Lifecycle events attributes Section titled Lifecycle events attributes **Added in:** `astro@3.6.0` **Type:** `URL` Arbitrary data defined during navigation. This is the literal value passed on the `info` option of the `navigate()` function. **Type:** `Element | undefined` The element that triggered the navigation. This can be, for example, an `<a>` element that was clicked. When using the `navigate()` function, this will be the element specified in the call. **Type:** `Document` The document for the next page in the navigation. The contents of this document will be swapped in place of the contents of the current document. **Type:** `'push' | 'replace' | 'traverse'` Which kind of history navigation is happening. * `push`: a new `NavigationHistoryEntry` is being created for the new page. * `replace`: the current `NavigationHistoryEntry` is being replaced with an entry for the new page. * `traverse`: no `NavigationHistoryEntry` is created. The position in the history is changing. The direction of the traversal is given on the `direction` attribute **Type:** `Direction` The direction of the transition. * `forward`: navigating to the next page in the history or to a new page. * `back`: navigating to the previous page in the history. * Anything else some other listener might have set. **Type:** `URL` The URL of the page initiating the navigation. **Type:** `URL` The URL of the page being navigated to. This property can be modified, the value at the end of the lifecycle will be used in the `NavigationHistoryEntry` for the next page. **Type:** `FormData | undefined` A `FormData` object for `POST` requests. When this attribute is set, a `POST` request will be sent to the `to` URL with the given form data object as the content instead of the normal `GET` request. When submitting an HTML form with view transitions enabled, this field is automatically set to the data in the form. When using the `navigate()` function, this value is the same as given in the options. **Type:** `() => Promise<void>` Implementation of the following phase in the navigation (loading the next page). This implementation can be overridden to add extra behavior. **Type:** `ViewTransition` The view transition object used in this navigation. On browsers that do not support the View Transitions API, this is an object implementing the same API for convenience but without the DOM integration. **Type:** `() => void` Implementation of the document swap logic. Read more about building a custom swap function in the View Transitions guide. By default, this implementation will call the following functions in order: 1. `deselectScripts()` 2. `swapRootAttributes()` 3. `swapHeadElements()` 4. `saveFocus()` 5. `swapBodyElement()` --- ## Page: https://docs.astro.build/en/reference/integrations-reference/ **Astro Integrations** add new functionality and behaviors for your project with only a few lines of code. This reference page is for anyone writing their own integration. To learn how to use an integration in your project, check out our Using Integrations guide instead. The official Astro integrations can act as reference for you as you go to build your own integrations. * **Renderers:** `svelte`, `react`, `preact`, `vue`, `solid` * **Libraries:** `partytown` * **Features:** `sitemap` ## Quick API Reference Section titled Quick API Reference interface AstroIntegration { name: string; hooks: { 'astro:config:setup'?: (options: { config: AstroConfig; command: 'dev' | 'build' | 'preview' | 'sync'; isRestart: boolean; updateConfig: (newConfig: DeepPartial<AstroConfig>) => AstroConfig; addRenderer: (renderer: AstroRenderer) => void; addWatchFile: (path: URL | string) => void; addClientDirective: (directive: ClientDirectiveConfig) => void; addMiddleware: (middleware: AstroIntegrationMiddleware) => void; addDevToolbarApp: (entrypoint: DevToolbarAppEntry) => void; injectScript: (stage: InjectedScriptStage, content: string) => void; injectRoute: (injectedRoute: InjectedRoute) => void; createCodegenDir: () => URL; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:route:setup'?: (options: { route: RouteOptions; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:routes:resolved'?: (options: { routes: IntegrationResolvedRoute[]; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:config:done'?: (options: { config: AstroConfig; setAdapter: (adapter: AstroAdapter) => void; injectTypes: (injectedType: InjectedType) => URL; logger: AstroIntegrationLogger; buildOutput: 'static' | 'server'; }) => void | Promise<void>; 'astro:server:setup'?: (options: { server: vite.ViteDevServer; logger: AstroIntegrationLogger; toolbar: ReturnType<typeof getToolbarServerCommunicationHelpers>; refreshContent?: (options: RefreshContentOptions) => Promise<void>; }) => void | Promise<void>; 'astro:server:start'?: (options: { address: AddressInfo; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:server:done'?: (options: { logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:start'?: (options: { logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:setup'?: (options: { vite: vite.InlineConfig; pages: Map<string, PageBuildData>; target: 'client' | 'server'; updateConfig: (newConfig: vite.InlineConfig) => void; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:ssr'?: (options: { manifest: SerializedSSRManifest; entryPoints: Map<IntegrationRouteData, URL>; middlewareEntryPoint: URL | undefined; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:generated'?: (options: { dir: URL; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:done'?: (options: { pages: { pathname: string }[]; dir: URL; assets: Map<string, URL[]>; logger: AstroIntegrationLogger; }) => void | Promise<void>; // ... any custom hooks from integrations };} Astro provides hooks that integrations can implement to execute during certain parts of Astro’s lifecycle. Astro hooks are defined in the `IntegrationHooks` interface, which is part of the global `Astro` namespace. Each hook has a `logger` option that allows you to use the Astro logger to write logs. The following hooks are built in to Astro: ### `astro:config:setup` Section titled astro:config:setup **Next hook:** `astro:route:setup` **When:** On initialization, before either the Vite or Astro config have resolved. **Why:** To extend the project config. This includes updating the Astro config, applying Vite plugins, adding component renderers, and injecting scripts onto the page. 'astro:config:setup'?: (options: { config: AstroConfig; command: 'dev' | 'build' | 'preview' | 'sync'; isRestart: boolean; updateConfig: (newConfig: DeepPartial<AstroConfig>) => AstroConfig; addRenderer: (renderer: AstroRenderer) => void; addClientDirective: (directive: ClientDirectiveConfig) => void; addMiddleware: (middleware: AstroIntegrationMiddleware) => void; addDevToolbarApp: (entrypoint: DevToolbarAppEntry) => void; addWatchFile: (path: URL | string) => void; injectScript: (stage: InjectedScriptStage, content: string) => void; injectRoute: (injectedRoute: InjectedRoute) => void; createCodegenDir: () => URL; logger: AstroIntegrationLogger;}) => void | Promise<void>; **Type:** `AstroConfig` A read-only copy of the user-supplied Astro config. This is resolved _before_ any other integrations have run. If you need a copy of the config after all integrations have completed their config updates, see the `astro:config:done` hook. **Type:** `'dev' | 'build' | 'preview' | 'sync'` * `dev` - Project is executed with `astro dev` * `build` - Project is executed with `astro build` * `preview` - Project is executed with `astro preview` * `sync` - Project is executed with `astro sync` #### `isRestart` option Section titled isRestart option **Type:** `boolean` **Added in:** `astro@1.5.0` `false` when the dev server starts, `true` when a reload is triggered. Useful to detect when this function is called more than once. #### `updateConfig()` option Section titled updateConfig() option **Type:** `(newConfig: DeepPartial<AstroConfig>) => AstroConfig;` A callback function to update the user-supplied Astro config. Any config you provide **will be merged with the user config + other integration config updates,** so you are free to omit keys! For example, say you need to supply a Vite plugin to the user’s project: import bananaCSS from '@vitejs/official-banana-css-plugin';export default { name: 'banana-css-integration', hooks: { 'astro:config:setup': ({ updateConfig }) => { updateConfig({ vite: { plugins: [bananaCSS()], } }) } }} #### `addRenderer()` option Section titled addRenderer() option **Type:** `(renderer:` `AstroRenderer` `) => void;` **Examples:** `svelte`, `react`, `preact`, `vue`, `solid` A callback function to add a component framework renderer (i.e. React, Vue, Svelte, etc). You can browse the examples and type definition above for more advanced options, but here are the 2 main options to be aware of: * `clientEntrypoint` - path to a file that executes on the client whenever your component is used. This is mainly for rendering or hydrating your component with JS. * `serverEntrypoint` - path to a file that executes during server-side requests or static builds whenever your component is used. These should render components to static markup, with hooks for hydration where applicable. React’s `renderToString` callback is a classic example. **Added in:** `astro@5.0.0` The functions `clientEntrypoint` and `serverEntrypoint` accept a `URL`. #### `addWatchFile()` option Section titled addWatchFile() option **Type:** `(path: URL | string) => void` **Added in:** `astro@1.5.0` If your integration depends on some configuration file that Vite doesn’t watch and/or needs a full dev server restart to take effect, add it with `addWatchFile`. Whenever that file changes, the Astro dev server will be reloaded (you can check when a reload happens with `isRestart`). Example usage: // Must be an absolute path!addWatchFile('/home/user/.../my-config.json');addWatchFile(new URL('./ec.config.mjs', config.root)); #### `addClientDirective()` option Section titled addClientDirective() option **Type:** `(directive:` `ClientDirectiveConfig` `) => void;` **Added in:** `astro@2.6.0` Adds a custom client directive to be used in `.astro` files. Note that directive entrypoints are only bundled through esbuild and should be kept small so they don’t slow down component hydration. Example usage: import { defineConfig } from 'astro/config';import clickDirective from './astro-click-directive/register.js'// https://astro.build/configexport default defineConfig({ integrations: [ clickDirective() ],}); /** * @type {() => import('astro').AstroIntegration} */export default () => ({ name: "client:click", hooks: { "astro:config:setup": ({ addClientDirective }) => { addClientDirective({ name: "click", entrypoint: "./astro-click-directive/click.js", }); }, },}); /** * Hydrate on first click on the window * @type {import('astro').ClientDirective} */export default (load, opts, el) => { window.addEventListener('click', async () => { const hydrate = await load() await hydrate() }, { once: true })} You can also add types for the directives in your library’s type definition file: import 'astro'declare module 'astro' { interface AstroClientDirectives { 'client:click'?: boolean }} #### `addDevToolbarApp()` option Section titled addDevToolbarApp() option **Type:** `(entrypoint: DevToolbarAppEntry) => void;` **Added in:** `astro@3.4.0` Adds a custom dev toolbar app. Example usage: import { defineConfig } from 'astro/config';import devToolbarIntegration from './astro-dev-toolbar-app/integration.js'// https://astro.build/configexport default defineConfig({ integrations: [ devToolbarIntegration() ],}); /** * @type {() => import('astro').AstroIntegration} */export default () => ({ name: "dev-toolbar-app", hooks: { "astro:config:setup": ({ addDevToolbarApp }) => { addDevToolbarApp({ entrypoint: "./astro-dev-toolbar-app/plugin.js", id: "my-plugin", name: "My Plugin" }); }, },}); /** * @type {import('astro').DevToolbarApp} */export default { id: "my-plugin", name: "My Plugin", icon: "<svg>...</svg>", init() { console.log("I'm a dev toolbar app!") },}; #### `addMiddleware()` option Section titled addMiddleware() option **Type:** `(middleware:` `AstroIntegrationMiddleware` `) => void;` **Added in:** `astro@3.5.0` Adds middleware to run on each request. Takes the `entrypoint` module that contains the middleware, and an `order` to specify whether it should run before (`pre`) other middleware or after (`post`). /** * @type {() => import('astro').AstroIntegration} */export default () => ({ name: "my-middleware-package", hooks: { "astro:config:setup": ({ addMiddleware }) => { addMiddleware({ entrypoint: '@my-package/middleware', order: 'pre' }); }, },}); Middleware is defined in a package with an `onRequest` function, as with user-defined middleware. import { defineMiddleware } from 'astro:middleware';export const onRequest = defineMiddleware(async (context, next) => { if(context.url.pathname === '/some-test-path') { return Response.json({ ok: true }); } return next();}); **Added in:** `astro@5.0.0` The function also accepts a `URL` for `entrypoint`: /** * @type {() => import('astro').AstroIntegration} */export default () => ({ name: "my-middleware-package", hooks: { "astro:config:setup": ({ addMiddleware }) => { addMiddleware({ entrypoint: new URL('./middleware.js', import.meta.url), order: 'pre' }); }, },}); #### `injectRoute()` option Section titled injectRoute() option **Type:** `({ pattern: string; entrypoint: string | URL; prerender?: boolean }) => void;` A callback function to inject routes into an Astro project. Injected routes can be `.astro` pages or `.js` and `.ts` route handlers. `injectRoute` takes an object with a `pattern` and an `entrypoint`. * `pattern` - where the route should be output in the browser, for example `/foo/bar`. A `pattern` can use Astro’s filepath syntax for denoting dynamic routes, for example `/foo/[bar]` or `/foo/[...bar]`. Note that a file extension is **not** needed in the `pattern`. * `entrypoint` - a bare module specifier pointing towards the `.astro` page or `.js`/`.ts` route handler that handles the route denoted in the `pattern`. * `prerender` - a boolean to set if Astro can’t detect your `prerender` export. injectRoute({ // Use Astro’s pattern syntax for dynamic routes. pattern: '/subfolder/[dynamic]', // Use relative path syntax for a local route. entrypoint: './src/dynamic-page.astro', // Use only if Astro can't detect your prerender export prerender: false}); For an integration designed to be installed in other projects, use its package name to refer to the route entrypoint. The following example shows a package published to npm as `@fancy/dashboard` injecting a dashboard route: injectRoute({ pattern: '/fancy-dashboard', entrypoint: '@fancy/dashboard/dashboard.astro'}); When publishing your package (`@fancy/dashboard`, in this case) to npm, you must export `dashboard.astro` in your `package.json`: { "name": "@fancy/dashboard", // ... "exports": { "./dashboard.astro": "./dashboard.astro" }} **Added in:** `astro@5.0.0` The function also accepts a `URL` for `entrypoint`: injectRoute({ pattern: '/fancy-dashboard', entrypoint: new URL('./dashboard.astro', import.meta.url)}); #### `injectScript()` option Section titled injectScript() option **Type:** `(stage: InjectedScriptStage, content: string) => void;` A callback function to inject a string of JavaScript content onto every page. The **`stage`** denotes how this script (the `content`) should be inserted. Some stages allow inserting scripts without modification, while others allow optimization during Vite’s bundling step: * `"head-inline"`: Injected into a script tag in the `<head>` of every page. **Not** optimized or resolved by Vite. * `"before-hydration"`: Imported client-side, before the hydration script runs. Optimized and resolved by Vite. * `"page"`: Similar to `head-inline`, except that the injected snippet is handled by Vite and bundled with any other `<script>` tags defined inside of Astro components on the page. The script will be loaded with a `<script type="module">` in the final page output, optimized and resolved by Vite. * `"page-ssr"`: Imported as a separate module in the frontmatter of every Astro page component. Because this stage imports your script, the `Astro` global is not available and your script will only be run once when the `import` is first evaluated. The main use for the `page-ssr` stage is injecting a CSS `import` into every page to be optimized and resolved by Vite: injectScript('page-ssr', 'import "global-styles.css";'); #### `createCodegenDir` Section titled createCodegenDir **Type:** `() => URL;` **Added in:** `astro@5.0.0` A function that creates the `<root>/.astro/integrations/<normalized_integration_name>` folder and returns its path. It allows you to have a dedicated folder, avoiding conflicts with another integration or Astro itself. This directory is created by calling this function so it’s safe to write files to it directly: import { writeFileSync } from 'node:fs'const integration = { name: 'my-integration', hooks: { 'astro:config:setup': ({ createCodegenDir }) => { const codegenDir = createCodegenDir() writeFileSync(new URL('cache.json', codegenDir), '{}', 'utf-8') } }} ### `astro:route:setup` Section titled astro:route:setup **Added in:** `astro@4.14.0` **Previous hook:** `astro:config:setup` **Next hook:** `astro:routes:resolved` **When:** In `astro build`, before bundling starts. In `astro dev`, while building the module graph and on every change to a file based route (added/removed/updated). **Why:** To set options for a route at build or request time, such as enabling on-demand server rendering. 'astro:route:setup'?: (options: { route: RouteOptions; logger: AstroIntegrationLogger;}) => void | Promise<void>; **Type:** `RouteOptions` An object with a `component` property to identify the route and the following additional values to allow you to configure the generated route: `prerender`. ##### `route.component` Section titled route.component **Type:** `string` **Added in:** `astro@4.14.0` The `component` property indicates the entrypoint that will be rendered on the route. You can access this value before the routes are built to configure on-demand server rendering for that page. ##### `route.prerender` Section titled route.prerender **Type:** `boolean` **Default:** `undefined` **Added in:** `astro@4.14.0` The `prerender` property is used to configure on-demand server rendering for a route. If the route file contains an explicit `export const prerender` value, the value will be used as the default instead of `undefined`. import { defineConfig } from 'astro/config';export default defineConfig({ integrations: [setPrerender()],});function setPrerender() { return { name: 'set-prerender', hooks: { 'astro:route:setup': ({ route }) => { if (route.component.endsWith('/blog/[slug].astro')) { route.prerender = true; } }, }, };} If the final value after running all the hooks is `undefined`, the route will fall back to a prerender default based on the `output` option: prerendered for `static` mode, and on-demand rendered for `server` mode. ### `astro:routes:resolved` Section titled astro:routes:resolved **Added in:** `astro@5.0.0` **Previous hook:** `astro:route:setup` **Next hook:** `astro:config:done` (only during setup) **When:** In `astro dev`, it also runs on every change to a file based route (added/removed/updated). **Why:** To access routes and their metadata 'astro:routes:resolved'?: (options: { routes: IntegrationResolvedRoute[]; logger: AstroIntegrationLogger;}) => void | Promise<void>; **Type:** `IntegrationResolvedRoute[]` A list of all routes with their associated metadata. Example use: const integration = () => { return { name: 'my-integration', hooks: { 'astro:routes:resolved': ({ routes }) => { const projectRoutes = routes.filter(r => r.origin === 'project').map(r => r.pattern) console.log(projectRoutes) }, } }} ### `astro:config:done` Section titled astro:config:done **Previous hook:** `astro:routes:resolved` **Next hook:** `astro:server:setup` when running in “dev” mode, or `astro:build:start` during production builds **When:** After the Astro config has resolved and other integrations have run their `astro:config:setup` hooks. **Why:** To retrieve the final config for use in other hooks. 'astro:config:done'?: (options: { config: AstroConfig; setAdapter: (adapter: AstroAdapter) => void; injectTypes: (injectedType: InjectedType) => URL; logger: AstroIntegrationLogger; buildOutput: 'static' | 'server';}) => void | Promise<void>; **Type:** `AstroConfig` A read-only copy of the user-supplied Astro config. This is resolved _after_ other integrations have run. #### `setAdapter()` option Section titled setAdapter() option **Type:** `(adapter: AstroAdapter) => void;` Makes the integration an adapter. Read more in the adapter API. #### `injectTypes()` option Section titled injectTypes() option **Type:** `(injectedType: { filename: string; content: string }) => URL` **Added in:** `astro@4.14.0` Allows you to inject types into your user’s project by adding a new `*.d.ts` file. The `filename` property will be used to generate a file at `/.astro/integrations/<normalized_integration_name>/<normalized_filename>.d.ts` and must end with `".d.ts"`. The `content` property will create the body of the file and must be valid TypeScript. Additionally, `injectTypes()` returns a URL to the normalized path so you can overwrite its content later on, or manipulate it in any way you want. const path = injectTypes({ filename: "types.d.ts", content: "declare module 'virtual:integration' {}"})console.log(path) // URL #### `buildOutput` option Section titled buildOutput option **Type:** `'static' | 'server'` **Added in:** `astro@5.0.0` Allows you to adapt the logic of your integration depending on the user’s project output. ### `astro:server:setup` Section titled astro:server:setup **Previous hook:** `astro:config:done` **Next hook:** `astro:server:start` **When:** Just after the Vite server is created in “dev” mode, but before the `listen()` event is fired. See Vite’s createServer API for more. **Why:** To update Vite server options and middleware, or enable support for refreshing the content layer. 'astro:server:setup'?: (options: { server: vite.ViteDevServer; logger: AstroIntegrationLogger; toolbar: ReturnType<typeof getToolbarServerCommunicationHelpers>; refreshContent: (options: { loaders?: Array<string>; context?: Record<string, any>; }) => Promise<void>;}) => void | Promise<void>; **Type:** `ViteDevServer` A mutable instance of the Vite server used in “dev” mode. For instance, this is used by our Partytown integration to inject the Partytown server as middleware: export default { name: 'partytown', hooks: { 'astro:server:setup': ({ server }) => { server.middlewares.use( function middleware(req, res, next) { // handle requests } ); } }} **Type:** `ReturnType<typeof getToolbarServerCommunicationHelpers>` **Added in:** `astro@4.7.0` An object providing callback functions to interact with the dev toolbar: **Type:** `<T>(event: string, callback: (data: T) => void) => void` A function that takes an event name as first argument and a callback function as second argument. This allows you to receive a message from a dev toolbar app with data associated to that event. ##### `onAppInitialized()` Section titled onAppInitialized() **Type:** `(appId: string, callback: (data: Record<string, never>) => void) => void` A function fired when a dev toolbar app is initialized. The first argument is the id of the app that was initialized. The second argument is a callback function to run when the app is initialized. **Type:** `(appId: string, callback: (data: { state: boolean; }) => void) => void` A function fired when a dev toolbar app is toggled on or off. The first argument is the id of the app that was toggled. The second argument is a callback function providing the state to execute when the application is toggled. **Type:** `<T>(event: string, payload: T) => void` A function that sends a message to the dev toolbar that an app can listen for. This takes an event name as the first argument and a payload as the second argument which can be any serializable data. #### `refreshContent()` option Section titled refreshContent() option **Type:** `(options: { loaders?: Array<string>; context?: Record<string, any>; }) => Promise<void>` **Added in:** `astro@5.0.0` A function for integrations to trigger an update to the content layer during `astro dev`. This can be used, for example, to register a webhook endpoint during dev, or to open a socket to a CMS to listen for changes. By default, `refreshContent` will refresh all collections. You can optionally pass a `loaders` property, which is an array of loader names. If provided, only collections that use those loaders will be refreshed. For example, A CMS integration could use this property to only refresh its own collections. You can also pass a `context` object to the loaders. This can be used to pass arbitrary data such as the webhook body, or an event from the websocket. { name: 'my-integration', hooks: { 'astro:server:setup': async ({ server, refreshContent }) => { // Register a dev server webhook endpoint server.middlewares.use('/_refresh', async (req, res) => { if(req.method !== 'POST') { res.statusCode = 405 res.end('Method Not Allowed'); return } let body = ''; req.on('data', chunk => { body += chunk.toString(); }); req.on('end', async () => { try { const webhookBody = JSON.parse(body); await refreshContent({ context: { webhookBody }, loaders: ['my-loader'] }); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ message: 'Content refreshed successfully' })); } catch (error) { res.writeHead(500, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Failed to refresh content: ' + error.message })); } }); }); } }} The loader can then access the `refreshContextData` property to get the webhook body. See the `refreshContextData` property for more information. ### `astro:server:start` Section titled astro:server:start **Previous hook:** `astro:server:setup` **Next hook:** `astro:server:done` **When:** Just after the server’s `listen()` event has fired. **Why:** To intercept network requests at the specified address. If you intend to use this address for middleware, consider using `astro:server:setup` instead. 'astro:server:start'?: (options: { address: AddressInfo; logger: AstroIntegrationLogger;}) => void | Promise<void>; **Type:** `AddressInfo` The address, family and port number supplied by the Node.js Net module. ### `astro:server:done` Section titled astro:server:done **Previous hook:** `astro:server:start` **When:** Just after the dev server is closed. **Why:** To run any cleanup events you may trigger during the `astro:server:setup` or `astro:server:start` hooks. 'astro:server:done'?: (options: { logger: AstroIntegrationLogger;}) => void | Promise<void>; ### `astro:build:start` Section titled astro:build:start **Previous hook:** `astro:config:done` **Next hook:** `astro:build:setup` **When:** After the `astro:config:done` event, but before the production build begins. **Why:** To set up any global objects or clients needed during a production build. This can also extend the build configuration options in the adapter API. 'astro:build:start'?: (options: { logger: AstroIntegrationLogger;}) => void | Promise<void>; ### `astro:build:setup` Section titled astro:build:setup **Previous hook:** `astro:build:start` **Next hook:** `astro:build:ssr` **When:** After the `astro:build:start` hook, runs immediately before the build. **Why:** At this point, the Vite config for the build has been completely constructed, this is your final chance to modify it. This can be useful for example to overwrite some defaults. If you’re not sure whether you should use this hook or `astro:build:start`, use `astro:build:start` instead. 'astro:build:setup'?: (options: { vite: vite.InlineConfig; pages: Map<string, PageBuildData>; target: 'client' | 'server'; updateConfig: (newConfig: vite.InlineConfig) => void; logger: AstroIntegrationLogger;}) => void | Promise<void>; **Type:** `InlineConfig` An object that allows you to access the Vite configuration used in the build. This can be useful if you need to access configuration options in your integration: export default { name: 'my-integration', hooks: { 'astro:build:setup': ({ vite }) => { const { publicDir, root } = vite; }, }} **Type:** `Map<string, PageBuildData>` A `Map` with a list of pages as key and their build data as value. This can be used to perform an action if a route matches a criteria: export default { name: 'my-integration', hooks: { 'astro:build:setup': ({ pages }) => { pages.forEach((data) => { if (data.route.pattern.test("/blog")) { console.log(data.route.type); } }); }, }} **Type:** `'client' | 'server'` Builds are separated in two distinct phases: `client` and `server`. This option allow you to determine the current build phase. This can be used to perform an action only in a specific phase: export default { name: 'my-integration', hooks: { 'astro:build:setup': ({ target }) => { if (target === "server") { // do something in server build phase } }, }} #### `updateConfig()` option Section titled updateConfig() option **Type:** `(newConfig: InlineConfig) => void` A callback function to update the Vite options used in the build. Any config you provide **will be merged with the user config + other integration config updates**, so you are free to omit keys! For example, this can be used to supply a plugin to the user’s project: import awesomeCssPlugin from 'awesome-css-vite-plugin';export default { name: 'my-integration', hooks: { 'astro:build:setup': ({ updateConfig }) => { updateConfig({ plugins: [awesomeCssPlugin()], }) } }} ### `astro:build:ssr` Section titled astro:build:ssr **Previous hook:** `astro:build:setup` **Next hook:** `astro:build:generated` **When:** After a production SSR build has completed. **Why:** To access the SSR manifest and map of the emitted entry points. This is useful when creating custom SSR builds in plugins or integrations. * `entryPoints` maps a page route to the physical file emitted after the build; * `middlewareEntryPoint` is the file system path of the middleware file; 'astro:build:ssr'?: (options: { manifest: SerializedSSRManifest; entryPoints: Map<IntegrationRouteData, URL>; middlewareEntryPoint: URL | undefined; logger: AstroIntegrationLogger;}) => void | Promise<void>; #### `manifest` option Section titled manifest option **Type:** `SerializedSSRManifest` Allows you to create a custom build by accessing the SSR manifest. export default { name: 'my-integration', hooks: { 'astro:build:ssr': ({ manifest }) => { const { i18n } = manifest; if (i18n?.strategy === "domains-prefix-always") { // do something } }, },} #### `entryPoints` option Section titled entryPoints option **Type:** `Map<IntegrationRouteData, URL>` **Added in:** `astro@2.7.0` A `Map` of the emitted entry points with the `IntegrationRouteData` as key and the physical file URL as value. export default { name: 'my-integration', hooks: { 'astro:build:ssr': ({ entryPoints }) => { entryPoints.forEach((url) => { console.log(url.href); }); }, },} #### `middlewareEntryPoint` option Section titled middlewareEntryPoint option **Type:** `URL | undefined` **Added in:** `astro@2.8.0` Exposes the middleware file path. export default { name: 'my-integration', hooks: { 'astro:build:ssr': ({ middlewareEntryPoint }) => { if (middlewareEntryPoint) { // do some operations if a middleware exist } }, },} ### `astro:build:generated` Section titled astro:build:generated **Added in:** `astro@1.3.0` **Previous hook:** `astro:build:ssr` **Next hook:** `astro:build:done` **When:** After a static production build has finished generating routes and assets. **Why:** To access generated routes and assets **before** build artifacts are cleaned up. This is a very uncommon use case. We recommend using `astro:build:done` unless you really need to access the generated files before cleanup. 'astro:build:generated'?: (options: { dir: URL; logger: AstroIntegrationLogger;}) => void | Promise<void>; **Type:** `URL` A URL path to the build output directory. Note that if you need a valid absolute path string, you should use Node’s built-in `fileURLToPath` utility. import { fileURLToPath } from 'node:url';export default { name: 'my-integration', hooks: { 'astro:build:generated': ({ dir }) => { const outFile = fileURLToPath(new URL('./my-integration.json', dir)); } }} ### `astro:build:done` Section titled astro:build:done **Previous hook:** `astro:build:generated` **When:** After a production build (SSG or SSR) has completed. **Why:** To access generated routes and assets for extension (ex. copy content into the generated `/assets` directory). If you plan to transform generated assets, we recommend exploring the Vite Plugin API and configuring via `astro:config:setup` instead. 'astro:build:done'?: (options: { pages: { pathname: string }[]; dir: URL; /** @deprecated Use the `assets` map and the new `astro:routes:resolved` hook */ routes: IntegrationRouteData[]; assets: Map<string, URL[]>; logger: AstroIntegrationLogger;}) => void | Promise<void>; **Type:** `URL` A URL path to the build output directory. Note that if you need a valid absolute path string, you should use Node’s built-in `fileURLToPath` utility. import { writeFile } from 'node:fs/promises';import { fileURLToPath } from 'node:url';export default function myIntegration() { return { hooks: { 'astro:build:done': async ({ dir }) => { const metadata = await getIntegrationMetadata(); // Use fileURLToPath to get a valid, cross-platform absolute path string const outFile = fileURLToPath(new URL('./my-integration.json', dir)); await writeFile(outFile, JSON.stringify(metadata)); } } }} **Type:** `IntegrationRouteData[]` A list of all generated routes alongside their associated metadata. You can reference the full `IntegrationRouteData` type below, but the most common properties are: * `component` - the input file path relative to the project root * `pathname` - the output file URL (undefined for routes using `[dynamic]` and `[...spread]` params) **Type:** `Map<string, URL[]>` **Added in:** `astro@5.0.0` Contains URLs to output files paths, grouped by `IntegrationResolvedRoute` `pattern` property. **Type:** `{ pathname: string }[]` A list of all generated pages. It is an object with one property. * `pathname` - the finalized path of the page. Custom hooks can be added to integrations by extending the `IntegrationHooks` interface through global augmentation. declare global { namespace Astro { export interface IntegrationHook { 'your:hook': (params: YourHookParameters) => Promise<void> } }} Astro reserves the `astro:` prefix for future built-in hooks. Please choose a different prefix when naming your custom hook. ## Integration types reference Section titled Integration types reference ### `AstroIntegrationLogger` Section titled AstroIntegrationLogger An instance of the Astro logger, useful to write logs. This logger uses the same log level configured via CLI. **Methods available** to write to terminal: * `logger.info("Message")`; * `logger.warn("Message")`; * `logger.error("Message")`; * `logger.debug("Message")`; All the messages are prepended with a label that has the same value as the name of the integration. import type { AstroIntegration } from "astro";export function formatIntegration(): AstroIntegration { return { name: "astro-format", hooks: { "astro:build:done": ({ logger }) => { // do something logger.info("Integration ready."); } } }} The example above will log a message that includes the provided `info` message: [astro-format] Integration ready. To log some messages with a different label, use the `.fork` method to specify an alternative to the default `name`: import type { AstroIntegration } from "astro";export function formatIntegration(): AstroIntegration { return { name: "astro-format", hooks: { "astro:config:done": ({ logger }) => { // do something logger.info("Integration ready."); }, "astro:build:done": ({ logger }) => { const buildLogger = logger.fork("astro-format/build"); // do something buildLogger.info("Build finished.") } } }} The example above will produce logs with `[astro-format]` by default, and `[astro-format/build]` when specified: [astro-format] Integration ready.[astro-format/build] Build finished. You can get the type of a hook’s arguments by passing the hook’s name to the `HookParameters` utility type. In the following example, a function’s `options` argument is typed to match the parameters of the `astro:config:setup` hook: import type { HookParameters } from 'astro';function mySetup(options: HookParameters<'astro:config:setup'>) { options.updateConfig({ /* ... */ });} ### `IntegrationResolvedRoute` type reference Section titled IntegrationResolvedRoute type reference interface IntegrationResolvedRoute { pattern: RouteData['route']; patternRegex: RouteData['pattern']; entrypoint: RouteData['component']; isPrerendered: RouteData['prerender']; redirectRoute?: IntegrationResolvedRoute; generate: (data?: any) => string; params: string[]; pathname?: string; segments: RoutePart[][]; type: RouteType; redirect?: RedirectConfig; origin: 'internal' | 'external' | 'project';} **Type:** `string` Allows you to identify the type of route based on its path. Here are some examples of paths associated with their pattern: * `src/pages/index.astro` will be `/` * `src/pages/blog/[...slug].astro` will be `/blog/[...slug]` * `src/pages/site/[blog]/[...slug].astro` will be `/site/[blog]/[...slug]` **Type:** `RegExp` Allows you to access a regex used for matching an input URL against a requested route. For example, given a `[fruit]/about.astro` path, the regex will be `/^\/([^/]+?)\/about\/?$/`. Using `pattern.test("banana/about")` will return `true`. **Type:** `string` The URL pathname of the source component. **Type:** `boolean` Determines whether the route use on demand rendering. The value will be `true` for projects configured with: * `output: 'static'` when the route does not export `const prerender = true` * `output: 'server'` when the route exports `const prerender = false` **Type:** `IntegrationResolvedRoute | undefined` When the value of `IntegrationResolvedRoute.type` is `redirect`, the value will be the `IntegrationResolvedRoute` to redirect to. Otherwise, the value will be undefined. **Type:** `(data?: any) => string` A function that provides the optional parameters of the route, interpolates them with the route pattern, and returns the path name of the route. For example, with a route such as `/blog/[...id].astro`, the `generate` function could return: console.log(generate({ id: 'presentation' })) // will log `/blog/presentation` **Type:** `string[]` Allows you to access the route `params`. For example, when a project uses the following dynamic routes `/pages/[lang]/[...slug].astro`, the value will be `['lang', '...slug']`. **Type:** `string | undefined` For regular routes, the value will be the URL pathname where this route will be served. When the project uses dynamic routes (ie. `[dynamic]` or `[...spread]`), the pathname will be undefined. **Type:** `RoutePart[][]` Allows you to access the route `params` with additional metadata. Each object contains the following properties: * `content`: the `param` name, * `dynamic`: whether the route is dynamic or not, * `spread`: whether the dynamic route uses the spread syntax or not. For example, the following route `/pages/[blog]/[...slug].astro` will output the segments: [ [ { content: 'pages', dynamic: false, spread: false } ], [ { content: 'blog', dynamic: true, spread: false } ], [ { content: '...slug', dynamic: true, spread: true } ]] **Type:** `RouteType` Allows you to identify the type of route. Possible values are: * `page`: a route that lives in the file system, usually an Astro component * `endpoint`: a route that lives in the file system, usually a JS file that exposes endpoints methods * `redirect`: a route points to another route that lives in the file system * `fallback`: a route that doesn’t exist in the file system that needs to be handled with other means, usually the middleware **Type:** `RedirectConfig | undefined` Allows you to access the route to redirect to. This can be a string or an object containing information about the status code and its destination. **Type:** `'internal' | 'external' | 'project'` Determines if a route comes from Astro core (`internal`), an integration (`external`) or the user’s project (`project`). ### `IntegrationRouteData` type reference Section titled IntegrationRouteData type reference A smaller version of the `RouteData` that is used in the integrations. interface IntegrationRouteData { type: RouteType; component: string; pathname?: string; pattern: RegExp; params: string[]; segments: { content: string; dynamic: boolean; spread: boolean; }[][]; generate: (data?: any) => string; prerender: boolean; distURL?: URL[]; redirect?: RedirectConfig; redirectRoute?: IntegrationRouteData;} **Type:** `RouteType` Allows you to identify the type of the route. The value can be: * `page`: a route that lives in the file system, usually an Astro component * `endpoint`: a route that lives in the file system, usually a JS file that exposes endpoints methods * `redirect`: a route that points to another route that lives in the file system * `fallback`: a route that doesn’t exist in the file system and needs to be handled with other means, usually middleware **Type:** `string` Allows you to access the source component URL pathname. **Type:** `string | undefined` For regular routes, the value will be the URL pathname where this route will be served. When the project uses dynamic routes (ie. `[dynamic]` or `[...spread]`), the pathname will be undefined. **Type:** `RegExp` Allows you to access a regex used for matching an input URL against a requested route. For example, given a `[fruit]/about.astro` path, the regex will be `/^\/([^/]+?)\/about\/?$/`. Using `pattern.test("banana/about")` will return `true`. **Type:** `string[]` Allows you to access the route `params`. For example, when a project uses the following dynamic routes `/pages/[lang]/[...slug].astro`, the value will be `['lang', '...slug']`. **Type:** `{ content: string; dynamic: boolean; spread: boolean; }[][]` Allows you to access the route `params` with additional metadata. Each object contains the following properties: * `content`: the `param`, * `dynamic`: whether the route is dynamic or not, * `spread`: whether the dynamic route uses the spread syntax or not. For example, the following route `/pages/[lang]/index.astro` will output the segments `[[ { content: 'lang', dynamic: true, spread: false } ]]`. **Type:** `(data?: any) => string` A function that provides the optional parameters of the route, interpolates them with the route pattern, and returns the path name of the route. For example, with a route such as `/blog/[...id].astro`, the `generate` function could return: console.log(generate({ id: 'presentation' })) // will log `/blog/presentation` **Type:** `boolean` Determines whether the route is prerendered or not. **Type:** `URL[] | undefined` The paths of the physical files emitted by this route. When a route **isn’t** prerendered, the value is either `undefined` or an empty array. **Type:** `RedirectConfig | undefined` Allows you to access the route to redirect to. This can be a string or an object containing information about the status code and its destination. **Type:** `IntegrationRouteData | undefined` When the value of `RouteData.type` is `redirect`, the value will contains the `IntegrationRouteData` of the route to redirect to. Otherwise, the value will be undefined. ## Allow installation with `astro add` Section titled Allow installation with astro add The `astro add` command allows users to easily add integrations and adapters to their project. If you want _your_ integration to be installable with this tool, **add `astro-integration` to the `keywords` field in your `package.json`**: { "name": "example", "keywords": ["astro-integration"],} Once you publish your integration to npm, running `astro add example` will install your package with any peer dependencies specified in your `package.json`. This will also apply your integration to the user’s `astro.config.*` like so: import { defineConfig } from 'astro/config';import example from 'example';export default defineConfig({ integrations: [example()],}) ## Integration Ordering Section titled Integration Ordering All integrations are run in the order that they are configured. For instance, for the array `[react(), svelte()]` in a user’s `astro.config.*`, `react` will run before `svelte`. Your integration should ideally run in any order. If this isn’t possible, we recommend documenting that your integration needs to come first or last in your user’s `integrations` configuration array. ## Combine integrations into presets Section titled Combine integrations into presets An integration can also be written as a collection of multiple, smaller integrations. We call these collections **presets.** Instead of creating a factory function that returns a single integration object, a preset returns an _array_ of integration objects. This is useful for building complex features out of multiple integrations. integrations: [ // Example: where examplePreset() returns: [integrationOne, integrationTwo, ...etc] examplePreset()] * Build your own Astro Integrations - by Emmanuel Ohans on FreeCodeCamp * Astro Integration Template - by Florian Lefebvre on GitHub --- ## Page: https://docs.astro.build/en/reference/adapter-reference/ Astro is designed to make it easy to deploy to any cloud provider for on-demand rendering, also known as server-side rendering (SSR). This ability is provided by **adapters**, which are integrations. See the on-demand rendering guide to learn how to use an existing adapter. ## What is an adapter? Section titled What is an adapter? An adapter is a special kind of integration that provides an entrypoint for server rendering at request time. An adapter does two things: * Implements host-specific APIs for handling requests. * Configures the build according to host conventions. ## Building an Adapter Section titled Building an Adapter An adapter is an integration and can do anything that an integration can do. An adapter **must** call the `setAdapter` API in the `astro:config:done` hook like so: export default function createIntegration() { return { name: '@matthewp/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@matthewp/my-adapter', serverEntrypoint: '@matthewp/my-adapter/server.js', supportedAstroFeatures: { staticOutput: 'stable' } }); }, }, };} The object passed into `setAdapter` is defined as: interface AstroAdapter { name: string; serverEntrypoint?: string; previewEntrypoint?: string; exports?: string[]; args?: any; adapterFeatures?: AstroAdapterFeatures; supportedAstroFeatures: AstroAdapterFeatureMap;}export interface AstroAdapterFeatures { /** * Creates an edge function that will communicate with the Astro middleware. */ edgeMiddleware: boolean; /** * Determine the type of build output the adapter is intended for. Defaults to `server`; */ buildOutput?: 'static' | 'server';}export type AdapterSupportsKind = 'unsupported' | 'stable' | 'experimental' | 'deprecated' | 'limited';export type AdapterSupportWithMessage = { support: Exclude<AdapterSupportsKind, 'stable'>; message: string;};export type AdapterSupport = AdapterSupportsKind | AdapterSupportWithMessage;export type AstroAdapterFeatureMap = { /** * The adapter is able to serve static pages */ staticOutput?: AdapterSupport; /** * The adapter is able to serve pages that are static or rendered via server */ hybridOutput?: AdapterSupport; /** * The adapter is able to serve pages rendered on demand */ serverOutput?: AdapterSupport; /** * The adapter is able to support i18n domains */ i18nDomains?: AdapterSupport; /** * The adapter is able to support `getSecret` exported from `astro:env/server` */ envGetSecret?: AdapterSupport; /** * The adapter supports the Sharp image service */ sharpImageService?: AdapterSupport;}; The properties are: * **name**: A unique name for your adapter, used for logging. * **serverEntrypoint**: The entrypoint for on-demand server rendering. * **exports**: An array of named exports when used in conjunction with `createExports` (explained below). * **adapterFeatures**: An object that enables specific features that must be supported by the adapter. These features will change the built output, and the adapter must implement the proper logic to handle the different output. * **supportedAstroFeatures**: A map of Astro built-in features. This allows Astro to determine which features an adapter is unable or unwilling to support so appropriate error messages can be provided. ### Server Entrypoint Section titled Server Entrypoint Astro’s adapter API attempts to work with any type of host, and gives a flexible way to conform to the host APIs. Some serverless hosts expect you to export a function, such as `handler`: export function handler(event, context) { // ...} With the adapter API you achieve this by implementing `createExports` in your `serverEntrypoint`: import { App } from 'astro/app';export function createExports(manifest) { const app = new App(manifest); const handler = (event, context) => { // ... }; return { handler };} And then in your integration, where you call `setAdapter`, provide this name in `exports`: export default function createIntegration() { return { name: '@matthewp/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@matthewp/my-adapter', serverEntrypoint: '@matthewp/my-adapter/server.js', exports: ['handler'], }); }, }, };} Some hosts expect you to _start_ the server yourselves, for example by listening to a port. For these types of hosts, the adapter API allows you to export a `start` function which will be called when the bundle script is run. import { App } from 'astro/app';export function start(manifest) { const app = new App(manifest); addEventListener('fetch', event => { // ... });} This module is used for rendering pages that have been prebuilt through `astro build`. Astro uses the standard Request and Response objects. Hosts that have a different API for request/response should convert to these types in their adapter. import { App } from 'astro/app';import http from 'http';export function start(manifest) { const app = new App(manifest); addEventListener('fetch', event => { event.respondWith( app.render(event.request) ); });} The following methods are provided: **Type:** `(request: Request, options?: RenderOptions) => Promise<Response>` This method calls the Astro page that matches the request, renders it, and returns a Promise to a Response object. This also works for API routes that do not render pages. const response = await app.render(request); **Type:** `{addCookieHeader?: boolean; clientAddress?: string; locals?: object; prerenderedErrorPageFetch?: (url: ErrorPagePath) => Promise<Response>; routeData?: RouteData;}` The `app.render()` method accepts a mandatory `request` argument, and an optional `RenderOptions` object for `addCookieHeader`, `clientAddress`, `locals`, `prerenderedErrorPageFetch`, and `routeData`. **Type:** `boolean` **Default:** `false` Whether or not to automatically add all cookies written by `Astro.cookie.set()` to the response headers. When set to `true`, they will be added to the `Set-Cookie` header of the response as comma separated key-value pairs. You can use the standard `response.headers.getSetCookie()` API to read them individually. When set to `false`(default), the cookies will only be available from `App.getSetCookieFromResponse(response)`. const response = await app.render(request, { addCookieHeader: true }); **Type:** `string` **Default:** `request[Symbol.for("astro.clientAddress")]` The client IP address that will be made available as `Astro.clientAddress` in pages, and as `ctx.clientAddress` in API routes and middleware. The example below reads the `x-forwarded-for` header and passes it as `clientAddress`. This value becomes available to the user as `Astro.clientAddress`. const clientAddress = request.headers.get("x-forwarded-for");const response = await app.render(request, { clientAddress }); **Type:** `object` The `context.locals` object used to store and access information during the lifecycle of a request. The example below reads a header named `x-private-header`, attempts to parse it as an object and pass it to `locals`, which can then be passed to any middleware function. const privateHeader = request.headers.get("x-private-header");let locals = {};try { if (privateHeader) { locals = JSON.parse(privateHeader); }} finally { const response = await app.render(request, { locals });} ###### `prerenderedErrorPageFetch` Section titled prerenderedErrorPageFetch **Type:** `(url: ErrorPagePath) => Promise<Response>` **Default:** `fetch` **Added in:** `astro@5.6.0` New A function that allows you to provide custom implementations for fetching prerendered error pages. This is used to override the default `fetch()` behavior, for example, when `fetch()` is unavailable or when you cannot call the server from itself. The following example reads `500.html` and `404.html` from disk instead of performing an HTTP call: return app.render(request, { prerenderedErrorPageFetch: async (url: string): Promise<Response> => { if (url.includes("/500")) { const content = await fs.promises.readFile("500.html", "utf-8"); return new Response(content, { status: 500, headers: { "Content-Type": "text/html" }, }); } const content = await fs.promises.readFile("404.html", "utf-8"); return new Response(content, { status: 404, headers: { "Content-Type": "text/html" }, });}); If not provided, Astro will fallback to its default behavior for fetching error pages. **Type:** `RouteData` **Default:** `app.match(request)` Provide a value for `integrationRouteData` if you already know the route to render. Doing so will bypass the internal call to `app.match` to determine the route to render. const routeData = app.match(request);if (routeData) { return app.render(request, { routeData });} else { /* adapter-specific 404 response */ return new Response(..., { status: 404 });} **Type:** `(request: Request) => RouteData | undefined` This method is used to determine if a request is matched by the Astro app’s routing rules. if(app.match(request)) { const response = await app.render(request);} You can usually call `app.render(request)` without using `.match` because Astro handles 404s if you provide a `404.astro` file. Use `app.match(request)` if you want to handle 404s in a different way. ## Allow installation via `astro add` Section titled Allow installation via astro add The `astro add` command allows users to easily add integrations and adapters to their project. If you want _your_ adapter to be installable with this tool, **add `astro-adapter` to the `keywords` field in your `package.json`**: { "name": "example", "keywords": ["astro-adapter"],} Once you publish your adapter to npm, running `astro add example` will install your package with any peer dependencies specified in your `package.json`. We will also instruct users to update their project config manually. **Added in:** `astro@3.0.0` Astro features are a way for an adapter to tell Astro whether they are able to support a feature, and also the adapter’s level of support. When using these properties, Astro will: * run specific validation; * emit contextual to the logs; These operations are run based on the features supported or not supported, their level of support, and the configuration that the user uses. The following configuration tells Astro that this adapter has experimental support for the Sharp-powered built-in image service: export default function createIntegration() { return { name: '@matthewp/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@matthewp/my-adapter', serverEntrypoint: '@matthewp/my-adapter/server.js', supportedAstroFeatures: { sharpImageService: 'experimental' } }); }, }, };} If the Sharp image service is used, Astro will log a warning and error to the terminal based on your adapter’s support: [@matthewp/my-adapter] The feature is experimental and subject to issues or changes.[@matthewp/my-adapter] The currently selected adapter `@matthewp/my-adapter` is not compatible with the service "Sharp". Your project will NOT be able to build. A message can additionally be provided to give more context to the user: export default function createIntegration() { return { name: '@matthewp/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@matthewp/my-adapter', serverEntrypoint: '@matthewp/my-adapter/server.js', supportedAstroFeatures: { sharpImageService: { support: 'limited', message: 'This adapter has limited support for Sharp, certain features may not work as expected.' } } }); }, }, };} ## Adapter features Section titled Adapter features A set of features that changes the output of the emitted files. When an adapter opts in to these features, they will get additional information inside specific hooks. **Type:** `boolean` Defines whether any on-demand rendering middleware code will be bundled when built. When enabled, this prevents middleware code from being bundled and imported by all pages during the build: export default function createIntegration() { return { name: '@matthewp/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@matthewp/my-adapter', serverEntrypoint: '@matthewp/my-adapter/server.js', adapterFeatures: { edgeMiddleware: true } }); }, }, };} Then, consume the hook `astro:build:ssr`, which will give you a `middlewareEntryPoint`, an `URL` to the physical file on the file system. export default function createIntegration() { return { name: '@matthewp/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@matthewp/my-adapter', serverEntrypoint: '@matthewp/my-adapter/server.js', adapterFeatures: { edgeMiddleware: true } }); }, 'astro:build:ssr': ({ middlewareEntryPoint }) => { // remember to check if this property exits, it will be `undefined` if the adapter doesn't opt in to the feature if (middlewareEntryPoint) { createEdgeMiddleware(middlewareEntryPoint) } } }, };}function createEdgeMiddleware(middlewareEntryPoint) { // emit a new physical file using your bundler} **Type:** `AdapterSupportsKind` This is a feature to allow your adapter to retrieve secrets configured by users in `env.schema`. Enable the feature by passing any valid `AdapterSupportsKind` value to the adapter: export default function createIntegration() { return { name: '@matthewp/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@matthewp/my-adapter', serverEntrypoint: '@matthewp/my-adapter/server.js', adapterFeatures: { envGetSecret: 'stable' } }); }, }, };} The `astro/env/setup` module allows you to provide an implementation for `getSecret()`. In your server entrypoint, call `setGetEnv()` as soon as possible: import { App } from 'astro/app';import { setGetEnv } from "astro/env/setup"setGetEnv((key) => process.env[key])export function createExports(manifest) { const app = new App(manifest); const handler = (event, context) => { // ... }; return { handler };} If you support secrets, be sure to call `setGetEnv()` before `getSecret()` when your environment variables are tied to the request: import type { SSRManifest } from 'astro';import { App } from 'astro/app';import { setGetEnv } from 'astro/env/setup';import { createGetEnv } from '../utils/env.js';type Env = { [key: string]: unknown;};export function createExports(manifest: SSRManifest) { const app = new App(manifest); const fetch = async (request: Request, env: Env) => { setGetEnv(createGetEnv(env)); const response = await app.render(request); return response; }; return { default: { fetch } };} **Type:** `'static' | 'server'` **Added in:** `astro@5.0.0` This property allows you to force a specific output shape for the build. This can be useful for adapters that only work with a specific output type, for instance, your adapter might expect a static website, but uses an adapter to create host-specific files. Defaults to `server` if not specified. export default function createIntegration() { return { name: '@matthewp/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@matthewp/my-adapter', serverEntrypoint: '@matthewp/my-adapter/server.js', adapterFeatures: { buildOutput: 'static' } }); }, }, };} --- ## Page: https://docs.astro.build/en/reference/content-loader-reference/ Astro’s Content Loader API allows you to load your data from any source, local or remote, and interact with Astro’s content layer to manage your content collections. ## What is a loader? Section titled What is a loader? Astro loaders allow you to load data into content collections, which can then be used in pages and components. The built-in `glob()` and `file()` loaders are used to load content from the file system, and you can create your own loaders to load content from other sources. Each collection needs a loader defined in its schema. You can define a loader inline in your project’s `src/content.config.ts` file, share one loader between multiple collections, or even publish your loader to NPM as a package to share with others and be included in our integrations library. ## Built-in loaders Section titled Built-in loaders Astro provides two built-in loaders to help you fetch your collections. Both offer options to suit a wide range of use cases. **Type:** `(options: GlobOptions) => Loader` **Added in:** `astro@5.0.0` The `glob()` loader creates entries from directories of files from anywhere on the filesystem. The supported file types are Markdown, MDX, Markdoc, JSON, and YAML files. This loader accepts an object with the following properties: `pattern`, `base` (optional), and `generateId` (optional). import { defineCollection } from 'astro:content';import { glob } from 'astro/loaders';const pages = defineCollection({ /* Retrieve all Markdown files in your pages directory. */ loader: glob({ pattern: "**/*.md", base: "./src/data/pages" }), schema: /* ... */});const blog = defineCollection({ /* Retrieve all Markdown and MDX files in your blog directory. */ loader: glob({ pattern: "**/*.(md|mdx)", base: "./src/data/blog" }), schema: /* ... */});const authors = defineCollection({ /* Retrieve all JSON files in your authors directory while retaining * uppercase letters in the ID. */ loader: glob({ pattern: '**/*.json', base: "./src/data/authors", generateId: ({ entry }) => entry.replace(/\.json$/, ''), }), schema: /* ... */}); **Type:** `string | string[]` The `pattern` property accepts a string or an array of strings using glob matching (e.g. wildcards, globstars). The patterns must be relative to the base directory of entry files to match. You can learn more about the syntax to use in the micromatch documentation. You can also verify the validity of your pattern using an online tool like the DigitalOcean Glob Tool. **Type:** `string | URL` **Default:** `"."` A relative path or URL to the directory from which to resolve the `pattern`. **Type:** `(options: GenerateIdOptions) => string` A callback function that returns a unique string per entry in a collection. It accepts an object as parameter with the following properties: * `entry` - the path to the entry file, relative to the base directory * `base` - the base directory URL * `data` - the parsed, unvalidated data of the entry By default it uses `github-slugger` to generate a slug with kebab-cased words. **Type:** `(fileName: string, options?: FileOptions) => Loader` **Added in:** `astro@5.0.0` The `file()` loader creates entries from a single file that contains an array of objects with a unique `id` field, or an object with IDs as keys and entries as values. It supports JSON or YAML, and you can provide a custom `parser` for data files it cannot parse by default. This loader accepts a `fileName` property and an optional object as second argument: import { defineCollection } from 'astro:content';import { file } from 'astro/loaders';const authors = defineCollection({ /* Retrieve all entries from a JSON file. */ loader: file("src/data/authors.json"), schema: /* ... */});const products = defineCollection({ /* Retrieve all entries from a CSV file using a custom parser. */ loader: file("src/data/products.csv", { parser: (fileContent) => { /* your parser logic */ }, }), schema: /* ... */}); **Type:** `string` Sets the path to the file to load, relative to the root directory. **Type:** `FileOptions` An optional object with the following properties: **Type:** `(text: string) => Record<string, Record<string, unknown>> | Array<Record<string, unknown>>` A callback function to create a collection from a file’s contents. Use it when you need to process file not supported by default (e.g. `.csv`) or when using nested `.json` documents. Loaders can be defined either as a simple function that returns an array of entries or with the more powerful object Content Loader API for more control over the loading process. An inline loader is an async function that returns an array or object containing entries. Use this for simple loaders, particularly those that are defined inline in the `src/content.config.ts` file. The function can be async and must return either an array of entries that each contain a unique `id` field, or an object where each key is a unique ID and each value is the entry. Whenever the loader is invoked, it will clear the store and reload all the entries. const countries = defineCollection({ loader: async () => { const response = await fetch("https://restcountries.com/v3.1/all"); const data = await response.json(); // Must return an array of entries with an id property // or an object with IDs as keys and entries as values return data.map((country) => ({ id: country.cca3, ...country, })); }, schema: /* ... */}); A loader is an object with a `load()` method that is called at build time to fetch data and update the data store. It allows entries to be updated incrementally, or for the store to be cleared only when necessary. It can also define a schema for the entries, which can be used to validate the data and generate static types. The recommended pattern is to define a function that accepts configuration options and returns the loader object, in the same way that you would normally define an Astro integration or Vite plugin. import type { Loader, LoaderContext } from 'astro/loaders';import { z } from 'astro:content';import { loadFeedData } from "./feed.js";// Define any options that the loader needsexport function myLoader(options: { url: string, apiKey: string }): Loader { // Configure the loader const feedUrl = new URL(options.url); // Return a loader object return { name: "my-loader", // Called when updating the collection. load: async (context: LoaderContext): Promise<void> => { // Load data and update the store const response = await loadFeedData(feedUrl, options.apiKey); }, // Optionally, define the schema of an entry. // It will be overridden by user-defined schema. schema: async () => z.object({ // ... }) };} These configuration options can then be set when defining a collection: import { defineCollection, z } from 'astro:content';import myLoader from '../../loader.ts';const blog = defineCollection({ loader: myLoader({ url: "https://api.example.com/posts", apiKey: "my-secret", }), schema: /* ... */}); ## Object loader API Section titled Object loader API The API for inline loaders is very simple, and is shown above. This section shows the API for defining an object loader. ### The `Loader` object Section titled The Loader object The loader object has the following properties: **Type**: `string` A unique name for the loader, used in logs and for conditional loading. **Type**: `(context: LoaderContext) => Promise<void>` An async function that is called at build time to load data and update the store. See `LoaderContext` for more information. **Type**: `ZodSchema | Promise<ZodSchema> | (() => ZodSchema | Promise<ZodSchema>)` An optional Zod schema that defines the shape of the entries. It is used to both validate the data and also to generate TypeScript types for the collection. If a function is provided, it will be called at build time before `load()` to generate the schema. You can use this to dynamically generate the schema based on the configuration options or by introspecting an API. This object is passed to the `load()` method of the loader, and contains the following properties: **Type**: `string` The unique name of the collection. This is the key in the `collections` object in the `src/content.config.ts` file. **Type**: `DataStore` A database to store the actual data. Use this to update the store with new entries. See `DataStore` for more information. **Type**: `MetaStore` A key-value store scoped to the collection, designed for things like sync tokens and last-modified times. This metadata is persisted between builds alongside the collection data but is only available inside the loader. const lastModified = meta.get("lastModified");// ...meta.set("lastModified", new Date().toISOString()); **Type**: `AstroIntegrationLogger` A logger that can be used to log messages to the console. Use this instead of `console.log` for more helpful logs that include the loader name in the log message. See `AstroIntegrationLogger` for more information. **Type**: `AstroConfig` The full, resolved Astro configuration object with all defaults applied. See the configuration reference for more information. **Type**: `(props: ParseDataOptions<TData>) => Promise<TData>` Validates and parses the data according to the collection schema. Pass data to this function to validate and parse it before storing it in the data store. import type { Loader } from "astro/loaders";import { loadFeed } from "./feed.js";export function feedLoader({ url }): Loader { const feedUrl = new URL(url); return { name: "feed-loader", load: async ({ store, logger, parseData, meta, generateDigest }) => { logger.info("Loading posts"); const feed = loadFeed(feedUrl); store.clear(); for (const item of feed.items) { const data = await parseData({ id: item.guid, data: item, }); store.set({ id, data, }); } }, };} **Type**: `(data: Record<string, unknown> | string) => string` Generates a non-cryptographic content digest of an object or string. This can be used to track if the data has changed by setting the `digest` field of an entry. import type { Loader } from "astro/loaders";import { loadFeed } from "./feed.js";export function feedLoader({ url }): Loader { const feedUrl = new URL(url); return { name: "feed-loader", load: async ({ store, logger, parseData, meta, generateDigest }) => { logger.info("Loading posts"); const feed = loadFeed(feedUrl); store.clear(); for (const item of feed.items) { const data = await parseData({ id: item.guid, data: item, }); const digest = generateDigest(data); store.set({ id, data, digest, }); } }, };} **Type**: `FSWatcher` When running in dev mode, this is a filesystem watcher that can be used to trigger updates. See `ViteDevServer` for more information. return { name: 'file-loader', load: async ({ config, store, watcher }) => { const url = new URL(fileName, config.root); const filePath = fileURLToPath(url); await syncData(filePath, store); watcher?.on('change', async (changedPath) => { if (changedPath === filePath) { logger.info(`Reloading data from ${fileName}`); await syncData(filePath, store); } }); },}; #### `refreshContextData` Section titled refreshContextData **Type**: `Record<string, unknown>` If the loader has been triggered by an integration, this may optionally contain extra data set by that integration. It is only set when the loader is triggered by an integration. See the `astro:server:setup` hook reference for more information. export function myLoader(options: { url: string }): Loader { return { name: "my-loader", load: async ({ refreshContextData, store, logger }) => { if(refreshContextData?.webhookBody) { logger.info("Webhook triggered with body"); processWebhook(store, refreshContextData.webhookBody); } // ... }, };} The data store is a loader’s interface to the content collection data. It is a key-value (KV) store, scoped to the collection, and therefore a loader can only access the data for its own collection. **Type**: `(key: string) => DataEntry | undefined` Get an entry from the store by its ID. Returns `undefined` if the entry does not exist. const existingEntry = store.get("my-entry"); The returned object is a `DataEntry` object. **Type**: `(entry: DataEntry) => boolean` Used after data has been validated and parsed to add an entry to the store, returning `true` if the entry was set. This returns `false` when the `digest` property determines that an entry has not changed and should not be updated. for (const item of feed.items) { const data = await parseData({ id: item.guid, data: item, }); const digest = generateDigest(data); store.set({ id, data, rendered: { html: data.description ?? "", }, digest, }); } **Type**: `() => Array<[id: string, DataEntry]>` Get all entries in the collection as an array of key-value pairs. **Type**: `() => Array<string>` Get all the keys of the entries in the collection. **Type**: `() => Array<DataEntry>` Get all entries in the collection as an array. **Type**: `(key: string) => void` Delete an entry from the store by its ID. **Type**: `() => void` Clear all entries from the collection. **Type**: `(key: string) => boolean` Check if an entry exists in the store by its ID. This is the type of the object that is stored in the data store. It has the following properties: **Type**: `string` An identifier for the entry, which must be unique within the collection. This is used to look up the entry in the store and is the key used with `getEntry` for that collection. **Type**: `Record<string, unknown>` The actual data for the entry. When a user accesses the collection, this will have TypeScript types generated according to the collection schema. It is the loader’s responsibility to use `parseData` to validate and parse the data before storing it in the data store: no validation is done when getting or setting the data. **Type**: `string | undefined` A path to the file that is the source of this entry, relative to the root of the site. This only applies to file-based loaders and is used to resolve paths such as images or other assets. If not set, then any fields in the schema that use the `image()` helper will be treated as public paths and not transformed. **Type**: `string | undefined` The raw body of the entry, if applicable. If the entry includes rendered content, then this field can be used to store the raw source. This is optional and is not used internally. **Type**: `string | undefined` An optional content digest for the entry. This can be used to check if the data has changed. When setting an entry, the entry will only update if the digest does not match an existing entry with the same ID. The format of the digest is up to the loader, but it must be a string that changes when the data changes. This can be done with the `generateDigest` function. **Type**: `RenderedContent | undefined` Stores an object with an entry’s rendered content and metadata if it has been rendered to HTML. For example, this can be used to store the rendered content of a Markdown entry, or HTML from a CMS. If this field is provided, then the `render()` function and `<Content />` component are available to render the entry in a page. The format of the `RenderedContent` object is: { /** Rendered HTML string. If present then `render(entry)` will return a component that renders this HTML. */ html: string; metadata?: { /** Any images that are present in this entry. Relative to the {@link DataEntry} filePath. */ imagePaths?: Array<string>; /** Any headings that are present in this file. Returned as `headings` from `render()` */ headings?: MarkdownHeading[]; /** Raw frontmatter, parsed from the file. This may include data from remark plugins. */ frontmatter?: Record<string, any>; /** Any other metadata that is present in this file. */ [key: string]: unknown; };} --- ## Page: https://docs.astro.build/en/reference/image-service-reference/ `astro:assets` was designed to make it easy for any image optimization service to build a service on top of Astro. ## What is an Image Service? Section titled What is an Image Service? Astro provides two types of image services: Local and External. * **Local services** handle image transformations directly at build for static sites, or at runtime both in development mode and for on-demand rendering. These are often wrappers around libraries like Sharp, ImageMagick, or Squoosh. In dev mode and in production routes rendered on demand, local services use an API endpoint to do the transformation. * **External services** point to URLs and can add support for services such as Cloudinary, Vercel, or any RIAPI\-compliant server. ## Building using the Image Services API Section titled Building using the Image Services API Service definitions take the shape of an exported default object with various required methods (“hooks”). External services provide a `getURL()` that points to the `src` of the output `<img>` tag. Local services provide a `transform()` method to perform transformations on your image, and `getURL()` and `parseURL()` methods to use an endpoint for dev mode and when rendered on demand. Both types of services can provide `getHTMLAttributes()` to determine the other attributes of the output `<img>` and `validateOptions()` to validate and augment the passed options. ### External Services Section titled External Services An external service points to a remote URL to be used as the `src` attribute of the final `<img>` tag. This remote URL is responsible for downloading, transforming, and returning the image. import type { ExternalImageService, ImageTransform, AstroConfig } from "astro";const service: ExternalImageService = { validateOptions(options: ImageTransform, imageConfig: AstroConfig['image']) { const serviceConfig = imageConfig.service.config; // Enforce the user set max width. if (options.width > serviceConfig.maxWidth) { console.warn(`Image width ${options.width} exceeds max width ${serviceConfig.maxWidth}. Falling back to max width.`); options.width = serviceConfig.maxWidth; } return options; }, getURL(options, imageConfig) { return `https://mysupercdn.com/${options.src}?q=${options.quality}&w=${options.width}&h=${options.height}`; }, getHTMLAttributes(options, imageConfig) { const { src, format, quality, ...attributes } = options; return { ...attributes, loading: options.loading ?? 'lazy', decoding: options.decoding ?? 'async', }; }};export default service; To create your own local service, you can point to the built-in endpoint (`/_image`), or you can additionally create your own endpoint that can call the service’s methods. import type { LocalImageService, AstroConfig } from "astro";const service: LocalImageService = { getURL(options: ImageTransform, imageConfig: AstroConfig['image']) { const searchParams = new URLSearchParams(); searchParams.append('href', typeof options.src === "string" ? options.src : options.src.src); options.width && searchParams.append('w', options.width.toString()); options.height && searchParams.append('h', options.height.toString()); options.quality && searchParams.append('q', options.quality.toString()); options.format && searchParams.append('f', options.format); return `/my_custom_endpoint_that_transforms_images?${searchParams}`; // Or use the built-in endpoint, which will call your parseURL and transform functions: // return `/_image?${searchParams}`; }, parseURL(url: URL, imageConfig) { return { src: params.get('href')!, width: params.has('w') ? parseInt(params.get('w')!) : undefined, height: params.has('h') ? parseInt(params.get('h')!) : undefined, format: params.get('f'), quality: params.get('q'), }; }, transform(buffer: Uint8Array, options: { src: string, [key: string]: any }, imageConfig): { data: Uint8Array, format: OutputFormat } { const { buffer } = mySuperLibraryThatEncodesImages(options); return { data: buffer, format: options.format, }; }, getHTMLAttributes(options, imageConfig) { let targetWidth = options.width; let targetHeight = options.height; if (typeof options.src === "object") { const aspectRatio = options.src.width / options.src.height; if (targetHeight && !targetWidth) { targetWidth = Math.round(targetHeight * aspectRatio); } else if (targetWidth && !targetHeight) { targetHeight = Math.round(targetWidth / aspectRatio); } } const { src, width, height, format, quality, ...attributes } = options; return { ...attributes, width: targetWidth, height: targetHeight, loading: attributes.loading ?? 'lazy', decoding: attributes.decoding ?? 'async', }; }, propertiesToHash: ['src', 'width', 'height', 'format', 'quality'],};export default service; At build time for static sites and pre-rendered routes, both `<Image />` and `getImage(options)` call the `transform()` function. They pass options either through component attributes or an `options` argument, respectively. The transformed images will be built to a `dist/_astro` folder. Their file names will contain a hash of the properties passed to `propertiesToHash`. This property is optional and will default to `['src', 'width', 'height', 'format', 'quality']`. If your custom image service has more options that change the generated images, add these to the array. In dev mode and when using an adapter to render on demand, Astro doesn’t know ahead of time which images need to be optimized. Astro uses a GET endpoint (by default, `/_image`) to process the images at runtime. `<Image />` and `getImage()` pass their options to `getURL()`, which will return the endpoint URL. Then, the endpoint calls `parseURL()` and passes the resulting properties to `transform()`. #### getConfiguredImageService & imageConfig Section titled getConfiguredImageService & imageConfig If you implement your own endpoint as an Astro endpoint, you can use `getConfiguredImageService` and `imageConfig` to call your service’s `parseURL` and `transform` methods and provide the image config. To access the image service config (`image.service.config`), you can use `imageConfig.service.config`. import type { APIRoute } from "astro";import { getConfiguredImageService, imageConfig } from 'astro:assets';export const GET: APIRoute = async ({ request }) => { const imageService = await getConfiguredImageService(); const imageTransform = imageService.parseURL(new URL(request.url), imageConfig); // ... fetch the image from imageTransform.src and store it in inputBuffer const { data, format } = await imageService.transform(inputBuffer, imageTransform, imageConfig); return new Response(data, { status: 200, headers: { 'Content-Type': mime.getType(format) || '' } } );} See the built-in endpoint for a full example. **Required for local and external services** `getURL(options: ImageTransform, imageConfig: AstroConfig['image']): string` For local services, this hook returns the URL of the endpoint that generates your image (for on-demand rendering and in dev mode). It is unused during build. The local endpoint that `getURL()` points to may call both `parseURL()` and `transform()`. For external services, this hook returns the final URL of the image. For both types of services, `options` are the properties passed by the user as attributes of the `<Image />` component or as options to `getImage()`. They are of the following type: export type ImageTransform = { // ESM imported images | remote/public image paths src: ImageMetadata | string; width?: number; height?: number; widths?: number[] | undefined; densities?: (number | `${number}x`)[] | undefined; quality?: ImageQuality; format?: OutputFormat; alt?: string; [key: string]: any;}; **Required for local services; unavailable for external services** `parseURL(url: URL, imageConfig: AstroConfig['image']): { src: string, [key: string]: any}` This hook parses the generated URLs by `getURL()` back into an object with the different properties to be used by `transform` (for on-demand rendering and in dev mode). It is unused during build. **Required for local services only; unavailable for external services** `transform(buffer: Uint8Array, options: { src: string, [key: string]: any }, imageConfig: AstroConfig['image']): { data: Uint8Array, format: OutputFormat }` This hook transforms and returns the image and is called during the build to create the final asset files. You must return a `format` to ensure that the proper MIME type is served to users for on-demand rendering and development mode. ### `getHTMLAttributes()` Section titled getHTMLAttributes() **Optional for both local and external services** `getHTMLAttributes(options: ImageTransform, imageConfig: AstroConfig['image']): Record<string, any>` This hook returns all additional attributes used to render the image as HTML, based on the parameters passed by the user (`options`). **Added in:** `astro@3.3.0` **Optional for both local and external services.** `getSrcSet?: (options: ImageTransform, imageConfig: AstroConfig['image']): SrcSetValue[] | Promise<SrcSetValue[]>;` This hook generates multiple variants of the specified image, for example, to generate a `srcset` attribute on an `<img>` or `<picture>`’s `source`. This hook returns an array of objects with the following properties: export type SrcSetValue = { transform: ImageTransform; descriptor?: string; attributes?: Record<string, any>;}; ### `validateOptions()` Section titled validateOptions() **Optional for both local and external services** `validateOptions(options: ImageTransform, imageConfig: AstroConfig['image']): ImageTransform` This hook allows you to validate and augment the options passed by the user. This is useful for setting default options, or telling the user that a parameter is required. See how `validateOptions()` is used in Astro built-in services. ## User configuration Section titled User configuration Configure the image service to use in `astro.config.mjs`. The config takes the following form: import { defineConfig } from "astro/config";export default defineConfig({ image: { service: { entrypoint: "your-entrypoint", // 'astro/assets/services/sharp' | string, config: { // ... service-specific config. Optional. } } },}); Astro exposes a number of helper functions that can be used to develop a custom image service. These utilities can be imported from `astro/assets/utils`: import { isRemoteAllowed, matchHostname, matchPathname, matchPattern, matchPort, matchProtocol, isESMImportedImage, isRemoteImage, resolveSrc, imageMetadata, emitESMImage, getOrigQueryParams, inferRemoteSize, propsToFilename, hashTransform} from "astro/assets/utils"; ### `isRemoteAllowed()` Section titled isRemoteAllowed() **Type:** `(src: string, { domains, remotePatterns }: {domains: string[], remotePatterns: RemotePattern[] }): boolean` **Added in:** `astro@4.0.0` Determines whether a given remote resource, identified by its source URL, is allowed based on specified domains and remote patterns. import { isRemoteAllowed } from 'astro/assets/utils';const testImageURL = '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];const url = new URL(testImageURL);const isAllowed = isRemoteAllowed(url.href, { domains, remotePatterns });console.log(`Is the remote image allowed? ${isAllowed}`); ### `matchHostname()` Section titled matchHostname() **Type:** `(url: URL, hostname?: string, allowWildcard = false): boolean` **Added in:** `astro@4.0.0` Matches a given URL’s hostname against a specified hostname, with optional support for wildcard patterns. import { matchHostname } from 'astro/assets/utils';const testURL = new URL('https://sub.example.com/path/to/resource');// Example usage of matchHostnameconst hostnameToMatch = 'example.com';// Match without wildcardconst isMatchWithoutWildcard = matchHostname(testURL, hostnameToMatch);console.log(`Does the hostname match without wildcard? ${isMatchWithoutWildcard}`); // Output: false// Match with wildcardconst isMatchWithWildcard = matchHostname(testURL, hostnameToMatch, true);console.log(`Does the hostname match with wildcard? ${isMatchWithWildcard}`); // Output: true ### `matchPathname()` Section titled matchPathname() **Type:** `(url: URL, pathname?: string, allowWildcard = false): boolean` **Added in:** `astro@4.0.0` Matches a given URL’s pathname against a specified pattern, with optional support for wildcards. import { matchPathname } from 'astro/assets/utils';const testURL = new URL('https://example.com/images/photo.jpg');// Example pathname to matchconst pathnameToMatch = '/images/photo.jpg';// Match without wildcardconst isMatchWithoutWildcard = matchPathname(testURL, pathnameToMatch);console.log(`Does the pathname match without wildcard? ${isMatchWithoutWildcard}`); // Output: true// Match with wildcardconst wildcardPathname = '/images/*';const isMatchWithWildcard = matchPathname(testURL, wildcardPathname, true);console.log(`Does the pathname match with wildcard? ${isMatchWithWildcard}`); // Output: true **Type:** `(url: URL, remotePattern: RemotePattern): boolean` **Added in:** `astro@4.0.0` Evaluates whether a given URL matches the specified remote pattern based on protocol, hostname, port, and pathname. import { matchPattern } from 'astro/assets/utils';const testURL = new URL('https://images.example.com/photos/test.jpg');// Define a remote pattern to match the URLconst remotePattern = { protocol: 'https', hostname: 'images.example.com', pathname: '/photos/**', // Wildcard to allow all files under /photos/ port: '', // Optional: Match any port or leave empty for default};// Check if the URL matches the remote patternconst isPatternMatched = matchPattern(testURL, remotePattern);console.log(`Does the URL match the remote pattern? ${isPatternMatched}`); // Output: true **Type:** `(url: URL, port?: string): boolean` **Added in:** `astro@4.0.0` Checks if the given URL’s port matches the specified port. If no port is provided, it returns `true`. import { matchPort } from 'astro/assets/utils';const testURL1 = new URL('https://example.com:8080/resource');const testURL2 = new URL('https://example.com/resource');// Example usage of matchPortconst portToMatch = '8080';// Match a URL with a port specifiedconst isPortMatch1 = matchPort(testURL1, portToMatch);console.log(`Does the port match? ${isPortMatch1}`); // Output: true// Match a URL without a port specified (default port will be assumed)const isPortMatch2 = matchPort(testURL2, portToMatch);console.log(`Does the port match? ${isPortMatch2}`); // Output: false// Check a URL without explicitly providing a port (defaults to true if port is undefined)const isPortMatch3 = matchPort(testURL1);console.log(`Does the port match (no port specified)? ${isPortMatch3}`); // Output: true ### `matchProtocol()` Section titled matchProtocol() **Type:** `(url: URL, protocol?: string): boolean` **Added in:** `astro@4.0.0` Compares the protocol of the provided URL with a specified protocol. import { matchProtocol } from 'astro/assets/utils';const testURL1 = new URL('https://example.com/resource');const testURL2 = new URL('http://example.com/resource');// Example usage of matchProtocolconst protocolToMatch = 'https';// Match a URL with correct protocolconst isProtocolMatch1 = matchProtocol(testURL1, protocolToMatch);console.log(`Does the protocol match for testURL1? ${isProtocolMatch1}`); // Output: true// Match a URL with incorrect protocolconst isProtocolMatch2 = matchProtocol(testURL2, protocolToMatch);console.log(`Does the protocol match for testURL2? ${isProtocolMatch2}`); // Output: false// Match a URL without explicitly providing a protocol (defaults to true if protocol is undefined)const isProtocolMatch3 = matchProtocol(testURL1);console.log(`Does the protocol match (no protocol specified)? ${isProtocolMatch3}`); // Output: true ### `isESMImportedImage()` Section titled isESMImportedImage() **Type:** `(src: ImageMetadata | string): boolean` **Added in:** `astro@4.0.0` Determines if the given source is an ECMAScript Module (ESM) imported image. import { isESMImportedImage } from 'astro/assets/utils';// Example usage of isESMImportedImageconst imageMetadataExample = { src: '/images/photo.jpg', width: 800, height: 600, format: 'jpg',};const filePathExample = '/images/photo.jpg';// Check if the input is an ESM imported imageconst isMetadataImage = isESMImportedImage(imageMetadataExample);console.log(`Is imageMetadataExample an ESM imported image? ${isMetadataImage}`); // Output: trueconst isFilePathImage = isESMImportedImage(filePathExample);console.log(`Is filePathExample an ESM imported image? ${isFilePathImage}`); // Output: false ### `isRemoteImage()` Section titled isRemoteImage() **Type:** `(src: ImageMetadata | string): boolean` **Added in:** `astro@4.0.0` Determines if the provided source is a remote image URL in the form of a string. import { isRemoteImage } from 'astro/assets/utils';// Example usage of isRemoteImageconst remoteImageUrl = 'https://example.com/images/photo.jpg';const localImageMetadata = { src: '/images/photo.jpg', width: 800, height: 600, format: 'jpg',};// Check if the input is a remote image URLconst isRemote1 = isRemoteImage(remoteImageUrl);console.log(`Is remoteImageUrl a remote image? ${isRemote1}`); // Output: trueconst isRemote2 = isRemoteImage(localImageMetadata);console.log(`Is localImageMetadata a remote image? ${isRemote2}`); // Output: false **Type:** `(src: UnresolvedImageTransform['src']): Promise<string | ImageMetadata>` **Added in:** `astro@4.0.0` 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. import { resolveSrc } from 'astro/assets/utils';import localImage from "./images/photo.jpg";const resolvedLocal = await resolveSrc(localImage);// will be `{ src: '/images/photo.jpg', width: 800, height: 600, format: 'jpg' }`const resolvedRemote = await resolveSrc("https://example.com/remote-img.jpg");// will be `"https://example.com/remote-img.jpg"`const resolvedDynamic = await resolveSrc(import("./images/dynamic-image.jpg"))// will be `{ src: '/images/dynamic-image.jpg', width: 800, height: 600, format: 'jpg' }` ### `imageMetadata()` Section titled imageMetadata() **Type:** `(data: Uint8Array, src?: string): Promise<Omit<ImageMetadata, 'src' | 'fsPath'>>` **Added in:** `astro@4.0.0` Extracts image metadata such as dimensions, format, and orientation from the provided image data. import { imageMetadata } from 'astro/assets/utils';async function extractImageMetadata() { // Example image data (Uint8Array) const exampleImageData = new Uint8Array([/* ...binary image data... */]); // Optional source path (useful for debugging or additional metadata context) const sourcePath = '/images/photo.jpg'; try { // Extract metadata from the image data const metadata = await imageMetadata(exampleImageData, sourcePath); console.log('Extracted Image Metadata:', metadata); // Example output: // { // width: 800, // height: 600, // format: 'jpg', // orientation: undefined // } } catch (error) { console.error('Failed to extract metadata from image:', error); }}await extractImageMetadata(); **Type:** `(id: string | undefined, _watchMode: boolean, experimentalSvgEnabled: boolean, fileEmitter?: FileEmitter): Promise<ImageMetadataWithContents | undefined>` **Added in:** `astro@4.0.0` 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. import { emitESMImage } from 'astro/assets/utils';const imageId = '/images/photo.jpg';const unusedWatchMode = false; // Deprecated, unusedconst unusedExperimentalSvgEnabled = false; // Set to `true` only if you are using SVG and want the file data to be embeddedtry { const result = await emitESMImage(imageId, unusedWatchMode, unusedExperimentalSvgEnabled); if (result) { console.log('Image metadata with contents:', result); // Example output: // { // width: 800, // height: 600, // format: 'jpg', // contents: Uint8Array([...]) // } } else { console.log('No metadata was emitted for this image.'); }} catch (error) { console.error('Failed to emit ESM image:', error);} ### `getOrigQueryParams()` Section titled getOrigQueryParams() **Type:** `(params: URLSearchParams): Pick<ImageMetadata, 'width' | 'height' | 'format'> | undefined` **Added in:** `astro@4.0.0` 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`. import { getOrigQueryParams } from 'astro/assets/utils';const url = new URL('https://example.com/image.jpg?width=800&height=600&format=jpg');const queryParams = url.searchParams;// Extract the original query parametersconst origParams = getOrigQueryParams(queryParams);if (origParams) { console.log('Original query parameters:', origParams); // Example output: // { // width: 800, // height: 600, // format: 'jpg' // }} else { console.log('Failed to extract original query parameters.');} ### `inferRemoteSize()` Section titled inferRemoteSize() **Type:** `(url: string): Promise<Omit<ImageMetadata, 'src' | 'fsPath'>>` **Added in:** `astro@4.0.0` Infers the dimensions of a remote image by streaming its data and analyzing it progressively until sufficient metadata is available. import { inferRemoteSize } from 'astro/assets/utils';async function getRemoteImageSize() { const remoteImageUrl = 'https://example.com/image.jpg'; try { // Infer remote image size from the URL const imageSize = await inferRemoteSize(remoteImageUrl); console.log('Inferred remote image size:', imageSize); // Example output: // { // width: 1920, // height: 1080, // format: 'jpg' // } } catch (error) { console.error('Failed to infer the size of the remote image:', error); }}await getRemoteImageSize(); ### `propsToFilename()` Section titled propsToFilename() **Type:** `(filePath: string, transform: ImageTransform, hash: string): string` **Added in:** `astro@4.0.0` 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 a `data:` URI. * `hash`: A unique hash string generated to distinguish the transformed file. * `outputExtension`: The desired output file extension derived from the `transform.format` or the original file extension. import { propsToFilename } from 'astro/assets/utils';function generateTransformedFilename() { const filePath = '/images/photo.jpg'; const transform = { format: 'png', src: '/images/photo.jpg' }; const hash = 'abcd1234'; // Generate the transformed filename based on the file path, transformation, and hash const filename = propsToFilename(filePath, transform, hash); console.log('Generated transformed filename:', filename); // Example output: '/images/photo_abcd1234.png'}generateTransformedFilename(); ### `hashTransform()` Section titled hashTransform() **Type:** `(transform: ImageTransform, imageService: string, propertiesToHash: string[]): string` **Added in:** `astro@4.0.0` Transforms the provided `transform` object into a hash string based on selected properties and the specified `imageService`. import { hashTransform } from 'astro/assets/utils';function generateTransformHash() { const transform = { width: 800, height: 600, format: 'jpg', }; const imageService = 'astroImageService'; const propertiesToHash = ['width', 'height', 'format']; // Generate the hash based on the transform, image service, and properties const hash = hashTransform(transform, imageService, propertiesToHash); console.log('Generated transform hash:', hash); // Example output: 'd41d8cd98f00b204e9800998ecf8427e'}generateTransformHash(); --- ## Page: https://docs.astro.build/en/reference/dev-toolbar-app-reference/ The Astro Dev Toolbar App API allows you to create Astro Integrations that add apps to the Astro Dev Toolbar. This allows you to add new features and integrations with third-party services. ## Toolbar app integration setup Section titled Toolbar app integration setup Integrations can add apps to the dev toolbar in the `astro:config:setup` hook. /** * @type {() => import('astro').AstroIntegration} */export default () => ({ name: "my-integration", hooks: { "astro:config:setup": ({ addDevToolbarApp }) => { addDevToolbarApp({ id: "my-app", name: "My App", icon: "<svg>...</svg>", entrypoint: "./my-app.js", }); }, },}); ### `addDevToolbarApp()` Section titled addDevToolbarApp() A function available to the `astro:config:setup` hook that adds dev toolbar apps. It takes an object with the following required properties to define the toolbar app: `id`, `name`, `icon`, and `entrypoint`. A unique identifier for the app. This will be used to uniquely identify the app in hooks and events. { id: 'my-app', // ...} The name of the app. This will be shown to users whenever the app needs to be referenced using a human-readable name. { // ... name: 'My App', // ...} The icon used to display the app in the toolbar. This can either be an icon from the icon list, or a string containing the SVG markup of the icon. { // ... icon: '<svg>...</svg>', // or, e.g. 'astro:logo' // ...} The path to the file that exports the dev toolbar app. { // ... entrypoint: './my-app.js',} **Added in:** `astro@5.0.0` The function also accepts a `URL` as `entrypoint`: /** * @type {() => import('astro').AstroIntegration} */export default () => ({ name: "my-integration", hooks: { "astro:config:setup": ({ addDevToolbarApp }) => { addDevToolbarApp({ id: "my-app", name: "My App", icon: "<svg>...</svg>", entrypoint: new URL("./my-app.js", import.meta.url), }); }, },}); ## Structure of a Dev Toolbar App Section titled Structure of a Dev Toolbar App A Dev Toolbar App is a `.js` or `.ts` file that default exports an object using the `defineToolbarApp()` function available from the `astro/toolbar` module. import { defineToolbarApp } from "astro/toolbar";export default defineToolbarApp({ init(canvas) { const text = document.createTextNode('Hello World!'); canvas.appendChild(text); }, beforeTogglingOff() { const confirmation = window.confirm('Really exit?'); return confirmation; }}); ### `defineToolbarApp()` Section titled defineToolbarApp() **Added in:** `astro@4.7.0` A function that defines the logic of your toolbar app when it is loaded and toggled off. This function takes an object with an `init()` function that will be called when the dev toolbar app is loaded. It can also take a `beforeTogglingOff()` function that will run when the toolbar app is clicked to toggle off its active status. **Signature:** `init(canvas: ShadowRoot, app: ToolbarAppEventTarget, server: ToolbarServerHelpers) => void` Although not required, most apps will use this function to define the core behavior of the app. This function will be called only once when the app is loaded, which will either be when the browser is idle or when the user clicks on the app in the UI, depending on which one comes first. The function receives three arguments to define your app logic: `canvas` (to render elements to the screen), `app` (to send and receive client-side events from the dev toolbar), and `server` (to communicate with the server). A standard ShadowRoot that the app can use to render its UI. Elements can be created and added to the ShadowRoot using the standard DOM APIs. Every app receives its own dedicated ShadowRoot for rendering its UI. Additionally, the parent element is positioned using `position: absolute;` so the app UI will not affect the layout of an Astro page. export default defineToolbarApp({ init(canvas) { canvas.appendChild(document.createTextNode('Hello World!')) }}); **Added in:** `astro@4.7.0` A standard `EventTarget` with a few additional helpers for client-side events that can be used to send and receive events from the Dev toolbar. export default defineToolbarApp({ init(canvas, app) { app.onToggled(({ state }) => { const text = document.createTextNode( `The app is now ${state ? "enabled" : "disabled"}!`, ); canvas.appendChild(text); }); },}); **Added in:** `astro@4.7.0` An object that can be used to communicate with the server. export default defineToolbarApp({ init(canvas, app, server) { server.send('my-message', { message: 'Hello!' }); server.on('server-message', (data) => { console.log(data.message); }); },}); ### `beforeTogglingOff()` Section titled beforeTogglingOff() **Signature:** `beforeTogglingOff(canvas: ShadowRoot): boolean | void` **Added in:** `astro@4.7.0` This optional function will be called when the user clicks on the app icon in the UI to toggle off the app. This function can be used, for example, to perform cleanup operations, or to ask the user for confirmation before toggling off the app. If a falsy value is returned, the toggling off will be cancelled and the app will stay enabled. export default defineToolbarApp({ // ... beforeTogglingOff() { const confirmation = window.confirm('Are you sure you want to disable this app?'); return confirmation; }}); The ShadowRoot of the app, can be used to render any UI needed before closing. Same as the `canvas` argument of the `init` function. ## Client-side Events Section titled Client-side Events In addition to the standard methods of an `EventTarget` (`addEventListener`, `dispatchEvent`, `removeEventListener`etc.), the `app` object also has the following methods: **Signature:** `onToggled(callback: (options: {state: boolean})) => void` **Added in:** `astro@4.7.0` Registers a callback to be called when the user clicks on the app icon in the UI to toggle the app on or off. app.onToggled((options) => { console.log(`The app is now ${options.state ? 'enabled' : 'disabled'}!`);}); ### `onToolbarPlacementUpdated()` Section titled onToolbarPlacementUpdated() **Signature:** `onToolbarPlacementUpdated(callback: (options: {placement: 'bottom-left' | 'bottom-center' | 'bottom-right'})) => void` **Added in:** `astro@4.7.0` This event is fired when the user changes the placement of the Dev Toolbar. This can, for example, be used to reposition the app’s UI when the toolbar is moved. app.onToolbarPlacementUpdated((options) => { console.log(`The toolbar is now placed at ${options.placement}!`);}); **Signature:** `toggleState(options: {state: boolean}) => void` **Added in:** `astro@4.7.0` Changes the state of the app. This can be used to enable or disable the app programmatically, for example, when the user clicks on a button in the app’s UI. app.toggleState({ state: false }); ### `toggleNotification()` Section titled toggleNotification() **Signature:** `toggleNotification(options: {state?: boolean, level?: 'error' | 'warning' | 'info'}) => void` **Added in:** `astro@4.7.0` Toggles a notification on the app icon. This can be used to inform the user that the app requires attention, or remove the current notification. app.toggleNotification({ state: true, level: 'warning',}); Indicates whether or not the app has a notification for the user. When `true`, the app icon will be highlighted. Conversely, when `false`, the highlight will be removed. If this property is not specified, `true` will be assumed. Indicates the level of the notification. This will be used to determine the color and shape (dark pink circle, gold triangle, or blue square) of the highlight on the app icon. If this property is not specified, `'error'` will be assumed. ## Client-Server Communication Section titled Client-Server Communication Using Vite’s methods for client-server communication, Dev Toolbar Apps and the server can communicate with each other. In order to facilitate sending and receiving custom messages, helper methods are provided for use both in your toolbar app (on the client) and in your integration (on the server). In your app, use the `server` object on the `init()` hook to send and receive messages to and from the server. export default defineToolbarApp({ init(canvas, app, server) { server.send('my-message', { message: 'Hello!' }); server.on('server-message', (data) => { console.log(data.message); }); },}); **Signature:** `send<T>(event: stringify, data: T) => void` **Added in:** `astro@4.7.0` Sends data to the server from logic defined in your toolbar app. init(canvas, app, server) { server.send('my-app:my-message', { message: 'Hello!' });} When sending messages from the client to the server, it is good practice to prefix the event name with the app ID or other namespaces to avoid conflicts with other apps or other integrations that may be listening for messages. **Signature:** `on<T>(event: string, callback: (data: T) => void) => void` **Added in:** `astro@4.7.0` Registers a callback to be called when the server sends a message with the specified event. init(canvas, app, server) { server.on('server-message', (data) => { console.log(data.message); });} In an integration, such as the integration that adds your toolbar app, use the `astro:server:setup` hook to access the `toolbar` object to send and receive messages to and from your apps. export default () => ({ name: "my-integration", hooks: { "astro:config:setup": ({ addDevToolbarApp }) => {}, "astro:server:setup": ({ toolbar }) => {}, },}); **Signature:** `send<T>(event: string, data: T) => void` **Added in:** `astro@4.7.0` Sends data to the client. 'astro:server:setup': ({ toolbar }) => { toolbar.send('server-message', { message: 'Hello!' });}, **Signature:** `on<T>(event: string, callback: (data: T) => void) => void` **Added in:** `astro@4.7.0` Registers a callback to be called when the client sends a message with the specified event. 'astro:server:setup': ({ toolbar }) => { toolbar.on('my-app:my-message', (data) => { console.log(data.message); });}, #### `onInitialized()` Section titled onInitialized() **Signature:** `onInitialized(appId: string, callback: () => void) => void` **Added in:** `astro@4.7.0` Registers a callback to be called when the app is initialized. 'astro:server:setup': ({ toolbar }) => { toolbar.onInitialized('my-app', () => { console.log('The app is now initialized!'); });}, **Signature:** `onAppToggled(appId: string, callback: (options: {state: boolean}) => void) => void` **Added in:** `astro@4.7.0` Registers a callback to be called when the user clicks on the app icon in the UI to toggle the app on or off. 'astro:server:setup': ({ toolbar }) => { toolbar.onAppToggled('my-app', ({ state }) => { console.log(`The app is now ${state ? 'enabled' : 'disabled'}!`); });}, ## Component Library Section titled Component Library The Dev Toolbar includes a set of web components that can be used to build apps with a consistent look and feel. ### `astro-dev-toolbar-window` Section titled astro-dev-toolbar-window Shows a window. The slot of the component will be used as the content of the window. <astro-dev-toolbar-window> <p>My content</p></astro-dev-toolbar-window> When building a window using JavaScript, slotted content must go inside the light DOM of the component. const myWindow = document.createElement('astro-dev-toolbar-window');const myContent = document.createElement('p');myContent.textContent = 'My content';// use appendChild directly on `window`, not `myWindow.shadowRoot`myWindow.appendChild(myContent); ### `astro-dev-toolbar-button` Section titled astro-dev-toolbar-button Shows a button. The slot of the component will be used as the content of the button. const myButton = document.createElement('astro-dev-toolbar-button');myButton.textContent = 'Click me!';myButton.buttonStyle = "purple";myButton.size = "medium";myButton.addEventListener('click', () => { console.log('Clicked!');}); The size of the button (`small`, `medium`, `large`). The style of the button (`ghost`, `outline`, `purple`, `gray`, `red`, `green`, `yellow`, `blue`). When using `ghost`, the button itself is invisible and only the content of the button will be shown. In JavaScript, set this property using the `buttonStyle` property to avoid conflict with the native `style` property. #### `button-border-radius` Section titled button-border-radius **Added in:** `astro@4.8.0` The border radius of the button (`normal`, `rounded`). When using `rounded`, the button will have rounded corners and uniform padding on all sides. In JavaScript, set this property using the `buttonBorderRadius` property. ### `astro-dev-toolbar-badge` Section titled astro-dev-toolbar-badge Shows a badge. The slot of the component will be used as the content of the badge. <astro-dev-toolbar-badge>My badge</astro-dev-toolbar-badge> The size of the badge (`small`, `large`). The style (color) of the badge (`purple`, `gray`, `red`, `green`, `yellow`, `blue`). In JavaScript, set this property using the `badgeStyle` property to avoid conflict with the native `style` property. ### `astro-dev-toolbar-card` Section titled astro-dev-toolbar-card Shows a card. Specify an optional `link` attribute to make the card act like an `<a>` element. When making a card using JavaScript, a `clickAction` property can be specified to make the card act like a `<button>` element. The slot of the component will be used as the content of the card. <astro-dev-toolbar-card icon="astro:logo" link="https://github.com/withastro/astro/issues/new/choose">Report an issue</astro-dev-toolbar-card> The style of the card (`purple`, `gray`, `red`, `green`, `yellow`, `blue`). The color is only applied to the border of the card on hover. In JavaScript, set this property using the `cardStyle`. ### `astro-dev-toolbar-toggle` Section titled astro-dev-toolbar-toggle Shows a toggle element, acting as a checkbox. This element internally is a simple wrapper around a native `<input type="checkbox">` element. The checkbox element can be accessed using the `input` property. const toggle = document.createElement('astro-dev-toolbar-toggle');toggle.input.addEventListener('change', (evt) => { console.log(`The toggle is now ${evt.currentTarget.checked ? 'enabled' : 'disabled'}!`);}); ### `astro-dev-toolbar-radio-checkbox` Section titled astro-dev-toolbar-radio-checkbox **Added in:** `astro@4.8.0` Shows a radio checkbox. Similar to the `astro-dev-toolbar-toggle` component, this element is a simple wrapper around a native `<input type="radio">` element. The radio element can be accessed using the `input` property. const radio = document.createElement('astro-dev-toolbar-radio-checkbox');radio.input.addEventListener('change', (evt) => { console.log(`The radio is now ${evt.currentTarget.checked ? 'enabled' : 'disabled'}!`);}); The style of the toggle (`purple`, `gray`, `red`, `green`, `yellow`, `blue`). In JavaScript, set this property using the `toggleStyle` property. ### `astro-dev-toolbar-highlight` Section titled astro-dev-toolbar-highlight Can be used to highlight an element on the page. In most cases, you’ll want to position and resize this element using the `top`, `left`, `width` and `height` CSS properties to match the element you want to highlight. <!-- Highlight the entire page --><astro-dev-toolbar-highlight style="top: 0; left: 0; width: 100%; height: 100%;"></astro-dev-toolbar-highlight> const elementToHighlight = document.querySelector('h1');const rect = elementToHighlight.getBoundingClientRect();const highlight = document.createElement('astro-dev-toolbar-highlight');highlight.style.top = `${Math.max(rect.top + window.scrollY - 10, 0)}px`;highlight.style.left = `${Math.max(rect.left + window.scrollX - 10, 0)}px`;highlight.style.width = `${rect.width + 15}px`;highlight.style.height = `${rect.height + 15}px`;highlight.icon = 'astro:logo'; The style of the highlight (`purple`, `gray`, `red`, `green`, `yellow`, `blue`). An icon to show in the top right corner of the highlight. ### `astro-dev-toolbar-tooltip` Section titled astro-dev-toolbar-tooltip Shows a tooltip with different sections. This component is set to `display: none;` by default and can be made visible using a `data-show="true"` attribute. Sections are defined using the `sections` property. This property is an array of objects with the following shape: { title?: string; // Title of the section inlineTitle?: string; // Title of the section, shown inline next to the title icon?: Icon; // Icon of the section content?: string; // Content of the section clickAction?: () => void | Promise<void>; // Action to perform when clicking on the section clickDescription?: string; // Description of the action to perform when clicking on the section} const tooltip = document.createElement('astro-dev-toolbar-tooltip');tooltip.sections = [{ title: 'My section', icon: 'astro:logo', content: 'My content', clickAction: () => { console.log('Clicked!') }, clickDescription: 'Click me!'}] This component is often combined with the `astro-dev-toolbar-highlight` component to show a tooltip when hovering a highlighted element: const highlight = document.createElement('astro-dev-toolbar-highlight');// Position the highlight...const tooltip = document.createElement('astro-dev-toolbar-tooltip');// Add sections to the tooltip...highlight.addEventListener('mouseover', () => { tooltip.dataset.show = 'true';});highlight.addEventListener('mouseout', () => { tooltip.dataset.show = 'false';}); ### `astro-dev-toolbar-icon` Section titled astro-dev-toolbar-icon Shows an icon. An icon from the icon list can be specified using the `icon` attribute, or the SVG markup of an icon can be passed as a slot. <astro-dev-toolbar-icon icon="astro:logo" /> <astro-dev-toolbar-icon> <svg>...</svg></astro-dev-toolbar-icon> Currently, the following icons are available and can be used in any component that accepts an icon: * `astro:logo` * `warning` * `arrow-down` * `bug` * `file-search` * `check-circle` * `gear` * `lightbulb` * `checkmark` * `dots-three` * `copy` All of the above icons have `fill="currentColor"` set by default and will inherit their color from the parent element. --- ## Page: https://docs.astro.build/en/reference/container-reference/ **Added in:** `astro@4.9.0` The Container API allows you to render Astro components in isolation. This experimental server-side API unlocks a variety of potential future uses, but is currently scoped to allow testing of `.astro` component output in `vite` environments such as `vitest`. It also allows you to manually load rendering scripts for creating containers in pages rendered on demand or other “shell” environments outside of `vite` (e.g. inside a PHP or Elixir application). This API allows you to create a new container, and render an Astro component returning a string or a `Response`. This API is experimental and subject to breaking changes, even in minor or patch releases. Please consult the Astro CHANGELOG for changes as they occur. This page will always be updated with the most current information for the latest version of Astro. Creates a new instance of the container. import { experimental_AstroContainer } from "astro/container";const container = await experimental_AstroContainer.create(); It accepts an object with the following options: export type AstroContainerOptions = { streaming?: boolean; renderers?: AddServerRenderer[];};export type AddServerRenderer = | { renderer: NamedSSRLoadedRendererValue; name: never; } | { renderer: SSRLoadedRendererValue; name: string; }; ### `streaming` option Section titled streaming option **Type:** `boolean` Enables rendering components using HTML streaming. ### `renderers` option Section titled renderers option **Type:** `AddServerRenderer[]` A list of loaded client renderers required by the component. Use this if your `.astro` component renders any UI framework components or MDX using an official Astro integration (e.g. React, Vue, etc.). Renderers can be added through the Container API automatically for static applications, or cases where the container isn’t called at runtime (e.g. testing with `vitest`). For on-demand rendered applications, or cases where the container is called at runtime or inside other “shells” (e.g. PHP, Ruby, Java, etc.), renderers must be manually imported. #### Adding a renderer through the Container API Section titled Adding a renderer through the Container API For each official Astro integration, import and use the `getContainerRenderer()` helper function to expose its client and server rendering scripts. These are available for `@astrojs/react`, `@astrojs/preact`, `@astrojs/solid-js`, `@astrojs/svelte`, `@astrojs/vue`, and `@astrojs/mdx`. For renderer packages outside the `@astrojs` npm org, look in their documentation for `getContainerRenderer()` or a similar function provided. When using `vite` (`vitest`, Astro integrations, etc.), the renderers are loaded with the function `loadRenderers()` from the virtual module `astro:container`. The following example provides the necessary object to render an Astro component that renders a React component and a Svelte component: import { getContainerRenderer as reactContainerRenderer } from "@astrojs/react";import { getContainerRenderer as svelteContainerRenderer } from "@astrojs/svelte";import { loadRenderers } from "astro:container";const renderers = await loadRenderers([reactContainerRenderer(), svelteContainerRenderer()]);const container = await experimental_AstroContainer.create({ renderers})const result = await container.renderToString(ReactWrapper); #### Adding a renderer manually Section titled Adding a renderer manually When the container is called at runtime, or inside other “shells”, the `astro:container` virtual module’s helper functions are not available. You must import the necessary server and client renderers manually and store them inside the container using `addServerRenderer` and `addClientRenderer`. Server renderers are required to build your project, and must be stored in the container for every framework used. Client renderers are additionally needed to any hydrate client-side components using `client:*` directives. Only one import statement is needed per framework. Importing a renderer makes both the server and client renderers available to your container. However, **server renderers must be added to your container before client renderers**. This allows your entire container to render first, and then hydrate any interactive components. The following example manually imports the necessary server renderers to be able to display static Vue components and `.mdx` pages. It additionally adds both server and client renderers for interactive React components. import reactRenderer from "@astrojs/react/server.js";import vueRenderer from "@astrojs/vue/server.js";import mdxRenderer from "@astrojs/mdx/server.js";const container = await experimental_AstroContainer.create();container.addServerRenderer({renderer: vueRenderer});container.addServerRenderer({renderer: mdxRenderer});container.addServerRenderer({ renderer: reactRenderer });container.addClientRenderer({ name: "@astrojs/react", entrypoint: "@astrojs/react/client.js" }); ## `renderToString()` Section titled renderToString() This function renders a specified component inside a container. It takes an Astro component as an argument and it returns a string that represents the HTML/content rendered by the Astro component. import { experimental_AstroContainer } from "astro/container";import Card from "../src/components/Card.astro";const container = await experimental_AstroContainer.create();const result = await container.renderToString(Card); Under the hood, this function calls `renderToResponse` and calls `Response.text()`. It also accepts an object as a second argument that can contain a number of options. ## `renderToResponse()` Section titled renderToResponse() It renders a component, and it returns a `Response` object. import { experimental_AstroContainer } from "astro/container";import Card from "../src/components/Card.astro";const container = await experimental_AstroContainer.create();const result = await container.renderToResponse(Card); It also accepts an object as a second argument that can contain a number of options. ## Rendering options Section titled Rendering options Both `renderToResponse` and `renderToString` accept an object as their second argument: export type ContainerRenderOptions = { slots?: Record<string, any>; props?: Record<string, unknown>; request?: Request; params?: Record<string, string | undefined>; locals?: App.Locals; routeType?: "page" | "endpoint";}; These optional values can be passed to the rendering function in order to provide additional information necessary for an Astro component to properly render. **Type**: `Record<string, any>`; An option to pass content to be rendered with `<slots>`. If your Astro component renders one default slot, pass an object with `default` as the key: import Card from "../src/components/Card.astro";const result = await container.renderToString(Card, { slots: { default: "Some value" }}); If your component renders named slots, use the slot names as the object keys: ------<div> <slot name="header" /> <slot name="footer" /></div> import Card from "../src/components/Card.astro";const result = await container.renderToString(Card, { slots: { header: "Header content", footer: "Footer" }}); You can also render components in cascade: ------<div> <slot name="header" /> <slot name="footer" /></div> import Card from "../src/components/Card.astro";import CardHeader from "../src/components/CardHeader.astro";import CardFooter from "../src/components/CardFooter.astro";const result = await container.renderToString(Card, { slots: { header: await container.renderToString(CardHeader), footer: await container.renderToString(CardFooter) }}); **Type**: `Record<string, unknown>` An option to pass properties for Astro components. import Card from "../src/components/Card.astro";const result = await container.renderToString(Card, { props: { name: "Hello, world!" }}); ---// For TypeScript supportinterface Props { name: string;};const { name } = Astro.props;---<div> {name}</div> **Type**: `Request` An option to pass a `Request` with information about the path/URL the component will render. Use this option when your component needs to read information like `Astro.url` or `Astro.request`. You can also inject possible headers or cookies. import Card from "../src/components/Card.astro";const result = await container.renderToString(Card, { request: new Request("https://example.com/blog", { headers: { "x-some-secret-header": "test-value" } })}); **Type**: `Record<string, string | undefined>`; An object to pass information about the path parameter to an Astro component responsible for generating dynamic routes. Use this option when your component needs a value for `Astro.params` in order to generate a single route dynamically. ---const { locale, slug } = Astro.params;---<div></div> import LocaleSlug from "../src/components/[locale]/[slug].astro";const result = await container.renderToString(LocaleSlug, { params: { locale: "en", slug: "getting-started" }}); **Type**: `App.Locals` An option to pass information from `Astro.locals` for rendering your component. Use this option to when your component needs information stored during the lifecycle of a request in order to render, such as logged in status. ---const { checkAuth } = Astro.locals;const isAuthenticated = checkAuth();---{isAuthenticated ? <span>You're in</span> : <span>You're out</span> } import Card from "../src/components/Card.astro";test("User is in", async () => { const result = await container.renderToString(Card, { locals: { checkAuth() { return true; } } }); // assert result contains "You're in"});test("User is out", async () => { const result = await container.renderToString(Card, { locals: { checkAuth() { return false; } } }); // assert result contains "You're out"}); ### `routeType` option Section titled routeType option **Type**: `"page" | "endpoint"` An option available when using `renderToResponse` to specify that you are rendering an endpoint: container.renderToString(Endpoint, { routeType: "endpoint" }); import * as Endpoint from "../src/pages/api/endpoint.js";const response = await container.renderToResponse(Endpoint, { routeType: "endpoint"});const json = await response.json(); To test your endpoint on methods such as `POST`, `PATCH`, etc., use the `request` option to call the correct function: export function GET() {}// need to test thisexport function POST() {} import * as Endpoint from "../src/pages/api/endpoint.js";const response = await container.renderToResponse(Endpoint, { routeType: "endpoint", request: new Request("https://example.com", { method: "POST" // Specify POST method for testing })});const json = await response.json(); **Type:** `boolean` **Default:** `true` **Added in:** `astro@4.16.6` Whether or not the Container API renders components as if they were page partials. This is usually the behavior you want when rendering `components.boolean` so you can render components without a full page shell. To render a component as a full Astro page, including `<!DOCTYPE html>`, you can opt-out of this behavior by setting `partial` to `false`: import Blog from "../src/pages/Blog.astro";const result = await container.renderToString(Card, { partial: false});console.log(result) // includes `<!DOCTYPE html>` at the beginning of the HTML --- ## Page: https://docs.astro.build/en/reference/programmatic-reference/ If you need more control when running Astro, the `"astro"` package exports APIs to programmatically run the CLI commands. These APIs are experimental and their API signature may change. Any updates will be mentioned in the Astro changelog and the information below will always show the current, up-to-date information. ## `AstroInlineConfig` Section titled AstroInlineConfig The `AstroInlineConfig` type is used by all of the command APIs below. It extends from the user Astro config type: interface AstroInlineConfig extends AstroUserConfig { configFile?: string | false; mode?: string; logLevel?: "debug" | "info" | "warn" | "error" | "silent";} **Type:** `string | false` **Default:** `undefined` A custom path to the Astro config file. If this value is undefined (default) or unset, Astro will search for an `astro.config.(js,mjs,ts,mts)` file relative to the `root` and load the config file if found. If a relative path is set, it will resolve based on the `root` option. Set to `false` to disable loading any config files. The inline config passed in this object will take highest priority when merging with the loaded user config. **Type:** `string` **Default:** `"development"` when running `astro dev`, `"production"` when running `astro build` **Added in:** `astro@5.0.0` The mode used when developing or building your site (e.g. `"production"`, `"testing"`). This value is passed to Vite using the `--mode` flag when the `astro build` or `astro dev` commands are run to determine the value of `import.meta.env.MODE`. This also determines which `.env` files are loaded, and therefore the values of `astro:env`. See the environment variables page for more details. To output a development-based build, you can run `astro build` with the `--devOutput` flag. **Type:** `"debug" | "info" | "warn" | "error" | "silent"` **Default:** `"info"` The logging level to filter messages logged by Astro. * `"debug"`: Log everything, including noisy debugging diagnostics. * `"info"`: Log informational messages, warnings, and errors. * `"warn"`: Log warnings and errors. * `"error"`: Log errors only. * `"silent"`: No logging. **Type:** `(inlineConfig: AstroInlineConfig) => Promise<DevServer>` Similar to `astro dev`, it runs Astro’s development server. import { dev } from "astro";const devServer = await dev({ root: "./my-project",});// Stop the server if neededawait devServer.stop(); export interface DevServer { address: AddressInfo; handle: (req: http.IncomingMessage, res: http.ServerResponse<http.IncomingMessage>) => void; watcher: vite.FSWatcher; stop(): Promise<void>;} **Type:** `AddressInfo` The address the dev server is listening on. This property contains the value returned by Node’s `net.Server#address()` method. **Type:** `(req: http.IncomingMessage, res: http.ServerResponse<http.IncomingMessage>) => void` A handle for raw Node HTTP requests. You can call `handle()` with an `http.IncomingMessage` and an `http.ServerResponse` instead of sending a request through the network. **Type:** `vite.FSWatcher` The Chokidar file watcher as exposed by Vite’s development server. **Type:** `Promise<void>` Stops the development server. This closes all idle connections and stops listening for new connections. Returns a `Promise` that resolves once all pending requests have been fulfilled and all idle connections have been closed. **Type:** `(inlineConfig: AstroInlineConfig, options?: BuildOptions) => Promise<void>` Similar to `astro build`, it builds your site for deployment. import { build } from "astro";await build({ root: "./my-project",}); export interface BuildOptions { devOutput?: boolean; teardownCompiler?: boolean;} **Type:** `boolean` **Default:** `false` **Added in:** `astro@5.4.0` Output a development-based build similar to code transformed in `astro dev`. This can be useful to test build-only issues with additional debugging information included. #### `teardownCompiler` Section titled teardownCompiler **Type:** `boolean` **Default:** `true` **Added in:** `astro@5.4.0` Teardown the compiler WASM instance after build. This can improve performance when building once but may cause a performance hit if building multiple times in a row. When building multiple projects in the same execution (e.g. during tests), disabling this option can greatly increase performance and reduce peak memory usage at the cost of higher sustained memory usage. **Type:** `(inlineConfig: AstroInlineConfig) => Promise<PreviewServer>` Similar to `astro preview`, it starts a local server to serve your build output. If no adapter is set in the configuration, the preview server will only serve the built static files. If an adapter is set in the configuration, the preview server is provided by the adapter. Adapters are not required to provide a preview server, so this feature may not be available depending on your adapter of choice. import { preview } from "astro";const previewServer = await preview({ root: "./my-project",});// Stop the server if neededawait previewServer.stop(); export interface PreviewServer { host?: string; port: number; closed(): Promise<void>; stop(): Promise<void>;} **Type:** `string` The host where the server is listening for connections. Adapters are allowed to leave this field unset. The value of `host` is implementation-specific. **Type:** `number` The port where the server is listening for connections. **Type:** `Promise<void>` Asks the preview server to close, stop accepting requests, and drop idle connections. The returned `Promise` resolves when the close request has been sent. This does not mean that the server has closed yet. Use the `closed()` method if you need to ensure the server has fully closed. **Type:** `Promise<void>` Returns a `Promise` that will resolve once the server is closed and reject if an error happens on the server. **Type:** `(inlineConfig: AstroInlineConfig) => Promise<void>` Similar to `astro sync`, it generates TypeScript types for all Astro modules. import { sync } from "astro";await sync({ root: "./my-project",}); **Type:** `<T extends AstroConfig | AstroInlineConfig>(config: T, overrides: DeepPartial<T>) => T` **Added in:** `astro@5.4.0` Imported from `astro/config`, merges a partial Astro configuration on top of an existing, valid, Astro configuration. `mergeConfig()` accepts an Astro config object and a partial config (any set of valid Astro config options), and returns a valid Astro config combining both values such that: * Arrays are concatenated (including integrations and remark plugins). * Objects are merged recursively. * Vite options are merged using Vite’s own `mergeConfig` function with the default `isRoot` flag. * Options that can be provided as functions are wrapped into new functions that recursively merge the return values from both configurations with these same rules. * All other options override the existing config. import { mergeConfig } from "astro/config";mergeConfig( { output: 'static', site: 'https://example.com', integrations: [partytown()], server: ({command}) => ({ port: command === 'dev' ? 4321 : 1234, }), build: { client: './custom-client', }, }, { output: 'server', base: '/astro', integrations: [mdx()], server: ({command}) => ({ host: command === 'dev' ? 'localhost' : 'site.localhost', }), build: { server: './custom-server', }, });// Result is equivalent to:{ output: 'server', site: 'https://example.com', base: '/astro', integrations: [partytown(), mdx()], server: ({command}) => ({ port: command === 'dev' ? 4321 : 1234, host: command === 'dev' ? 'localhost' : 'site.localhost', }), build: { client: './custom-client', server: './custom-server', },} ## `validateConfig()` Section titled validateConfig() **Type:** `(userConfig: any, root: string, cmd: string): Promise<AstroConfig>` **Added in:** `astro@5.4.0` Imported from `astro/config`, validates an object as if it was exported from `astro.config.mjs` and imported by Astro. It takes the following arguments: * The configuration to be validated. * The root directory of the project. * The Astro command that is being executed (`build`, `dev`, `sync`, etc.) The returned promise resolves to the validated configuration, filled with all default values appropriate for the given Astro command. import { validateConfig } from "astro/config";const config = await validateConfig({ integrations: [partytown()],}, "./my-project", "build");// defaults are appliedawait rm(config.outDir, { recursive: true, force: true }); --- ## Page: https://docs.astro.build/en/reference/experimental-flags/ Experimental features are available only after enabling a flag in the Astro configuration file. import { defineConfig } from 'astro/config';export default defineConfig({ experimental: { // enable experimental flags // to try out new features },}); Astro offers experimental flags to give users early access to new features for testing and feedback. These flags allow you to participate in feature development by reporting issues and sharing your opinions. These features are not guaranteed to be stable and may include breaking changes even in small `patch` releases while the feature is actively developed. We recommend updating Astro frequently, and keeping up with release notes in the Astro changelog which will inform you of any changes needed to your project code. The experimental feature documentation will always be updated for the current released version only. --- ## Page: https://docs.astro.build/en/reference/experimental-flags/responsive-images/ **Type:** `boolean` **Default:** `false` **Added in:** `astro@5.0.0` Enables support for automatic responsive images in your project. { experimental: { responsiveImages: true, },} With this flag enabled, you have access to additional `image` configuration settings for controlling the default behavior of all images processed and optimized by Astro: * Local and remote images using the Markdown `![]()` syntax. * The `<Image />` and `<Picture />` components. Additionally, Astro’s image components can receive responsive image props to override these defaults on a per-image basis. Images in your `public/` folder are never optimized, and responsive images are not supported. ## Responsive image configuration settings Section titled Responsive image configuration settings Set `image.experimentalLayout` with a default value (`responsive`, `fixed`, or `full-width`) to enable responsive images throughout your project. If this value is not configured, you can still pass a `layout` prop to any `<Image />` or `<Picture />` component to create a responsive image. However, Markdown images will not be responsive. Optionally, you can configure `image.experimentalObjectFit` and `image.experimentalObjectPosition` which will apply to all processed images by default. Each of these settings can be overridden on any individual `<Image />` or `<Picture />` component with a prop, but all Markdown images will always use the default settings. { image: { // Used for all Markdown images; not configurable per-image // Used for all `<Image />` and `<Picture />` components unless overridden with a prop experimentalLayout: 'responsive', }, experimental: { responsiveImages: true, },} ## Responsive image properties Section titled Responsive image properties These are additional properties available to the `<Image />` and `<Picture />` components when responsive images are enabled: * `layout`: The layout type for the image. Can be `responsive`, `fixed`, `full-width`, or `none`. Defaults to the value of `image.experimentalLayout`. * `fit`: Defines how the image should be cropped if the aspect ratio is changed. Values match those of CSS `object-fit`. Defaults to `cover`, or the value of `image.experimentalObjectFit` if set. * `position`: Defines the position of the image crop if the aspect ratio is changed. Values match those of CSS `object-position`. Defaults to `center`, or the value of `image.experimentalObjectPosition` if set. * `priority`: If set, eagerly loads the image. Otherwise, images will be lazy-loaded. Use this for your largest above-the-fold image. Defaults to `false`. The `widths` and `sizes` attributes are automatically generated based on the image’s dimensions and the layout type, and in most cases should not be set manually. The generated `sizes` attribute for `responsive` and `full-width` images is based on the assumption that the image is displayed at close to the full width of the screen when the viewport is smaller than the image’s width. If it is significantly different (e.g. if it’s in a multi-column layout on small screens) you may need to adjust the `sizes` attribute manually for best results. The `densities` attribute is not compatible with responsive images and will be ignored if set. For example, with `responsive` set as the default layout, you can override any individual image’s `layout` property: ---import { Image } from 'astro:assets';import myImage from '../assets/my_image.png';---<Image src={myImage} alt="This will use responsive 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" /> ## Generated HTML output for responsive images Section titled Generated HTML output for responsive images When a layout is set, either by default or on an individual component, images have automatically generated `srcset` and `sizes` attributes based on the image’s dimensions and the layout type. Images with `responsive` and `full-width` layouts will have styles applied to ensure they resize according to their container. ---import { Image, Picture } from 'astro:assets';import myImage from '../assets/my_image.png';---<Image src={myImage} alt="A description of my image." layout='responsive' width={800} height={600} /><Picture src={myImage} alt="A description of my image." layout='full-width' formats={['avif', 'webp', 'jpeg']} /> This `<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="--w: 800; --h: 600; --fit: cover; --pos: center;" data-astro-image="responsive"> The following styles are applied to ensure the images resize correctly: [data-astro-image] { width: 100%; height: auto; object-fit: var(--fit); object-position: var(--pos); aspect-ratio: var(--w) / var(--h)}[data-astro-image=responsive] { max-width: calc(var(--w) * 1px); max-height: calc(var(--h) * 1px)}[data-astro-image=fixed] { width: calc(var(--w) * 1px); height: calc(var(--h) * 1px)} For a complete overview, and to give feedback on this experimental API, see the Responsive Images RFC. Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/experimental-flags/svg/ **Type:** `boolean` **Default:** `false` **Added in:** `astro@5.0.0` This feature allows you to import SVG files and use them as Astro components. Astro will inline the SVG content into your HTML output. To enable this feature, set `experimental.svg` to `true` in your Astro config: { experimental: { svg: true, },} To use this feature, reference the default import of any local `.svg` file. Since this import is treated as an Astro component, you must use the same conventions (e.g. capitalization) as when using dynamic tags. ---import Logo from './path/to/svg/file.svg';---<Logo /> ## SVG component attributes Section titled SVG component attributes You can pass props such as `width`, `height`, `fill`, `stroke`, and any other attribute accepted by the native `<svg>` element. These attributes will automatically be applied to the underlying `<svg>` element. If a property is present in the original `.svg` file and is passed to the component, the value passed to the component will override the original value. ---import Logo from '../assets/logo.svg';---<Logo width={64} height={64} fill="currentColor" /> For a complete overview, and to give feedback on this experimental API, see the SVG feature RFC. Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/experimental-flags/client-prerender/ **Type:** `boolean` **Default:** `false` **Added in:** `astro@4.2.0` Enables pre-rendering your prefetched pages on the client in supported browsers. This feature uses the experimental Speculation Rules Web API and enhances the default `prefetch` behavior globally to prerender links on the client. You may wish to review the possible risks when prerendering on the client before enabling this feature. Enable client side prerendering in your `astro.config.mjs` along with any desired `prefetch` configuration options: { prefetch: { prefetchAll: true, defaultStrategy: 'viewport', }, experimental: { clientPrerender: true, },} Continue to use the `data-astro-prefetch` attribute on any `<a />` link on your site to opt in to prefetching. Instead of appending a `<link>` tag to the head of the document or fetching the page with JavaScript, a `<script>` tag will be appended with the corresponding speculation rules. Client side prerendering requires browser support. If the Speculation Rules API is not supported, `prefetch` will fallback to the supported strategy. See the Prefetch Guide for more `prefetch` options and usage. Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/experimental-flags/content-intellisense/ **Type:** `boolean` **Default:** `false` **Added in:** `astro@4.14.0` Enables Intellisense features (e.g. code completion, quick hints) for your content collection entries in compatible editors. When enabled, this feature will generate and add JSON schemas to the `.astro` directory in your project. These files can be used by the Astro language server to provide Intellisense inside content files (`.md`, `.mdx`, `.mdoc`). { experimental: { contentIntellisense: true, },} To use this feature with the Astro VS Code extension, you must also enable the `astro.content-intellisense` option in your VS Code settings. For editors using the Astro language server directly, pass the `contentIntellisense: true` initialization parameter to enable this feature. --- ## Page: https://docs.astro.build/en/reference/experimental-flags/sessions/ **Type:** `boolean` **Default:** `false` **Added in:** `astro@5.1.0` Sessions are used to store user state between requests for on-demand rendered pages. This experimental feature allows you to store and access items such as login status, shopping cart contents, or other user-specific data: ---export const prerender = false; // Not needed with 'server' outputconst cart = await Astro.session.get('cart');---<a href="/checkout">🛒 {cart?.length ?? 0} items</a> Sessions rely on a configurable session `driver` to store data on the `session` object. A session cookie stores an identifying session ID. The `session` object allows you to interact with the stored user state (e.g. add items to a shopping cart) and the session ID (e.g. delete the session ID cookie when logging out). ## Enabling experimental sessions Section titled Enabling experimental sessions To enable sessions, set the `experimental.session` flag to `true`. Sessions only work on pages with on-demand rendering, so you need to install an adapter that supports on-demand rendering, and ensure that any pages that use sessions are set to `prerender: false`, or `output` is set to `server` in the Astro config. { adapter: node({ mode: "standalone", }), experimental: { session: true, }, } Sessions require a storage driver to store the session data. The Node and Netlify adapters automatically configure a default driver for you, but other adapters currently require you to specify a driver manually. You can use any supported driver from unstorage. ### Configuring a session driver Section titled Configuring a session driver If you are using an adapter that doesn’t have a default driver, or if you want to choose a different driver, you can configure it using the `session` configuration option: { adapter: vercel(), session: { driver: "upstash", }, experimental: { session: true, }, } Configure `session.driver` with the unstorage `driver` name that corresponds to the storage feature provided by your hosting platform, such as the Cloudflare KV driver or the Deno KV driver. You can also use a cross-platform driver such as Upstash or Redis. You can also pass any available options to the unstorage driver in a separate `session.options` object. See your chosen driver’s documentation for available options. The following example sets a `base` prefix (`"sessions"`) to use for all keys in Upstash: { adapter: vercel(), session: { driver: "upstash", options: { base: "sessions", }, }, experimental: { session: true, }, } ### Other session options Section titled Other session options You can configure additional options for sessions in the `session` object. **Type:** `string` | `object` **Default:** `astro-session` Configures the session cookie. This cookie is set in the response when a session is generated. No actual user data is stored in the cookie – just an ID that is used to identify a user’s session. The `session.cookie` option can be used to set options for this cookie. You can either provide a `string`, which will be used as the cookie name, or an object which allows additional options: { session: { // If set to a string, this will be used as the cookie name // cookie: "my-session-id", // If set to an object, this will allow advanced options to be set cookie: { name: "my-session-id" sameSite: "Strict", }, } } **Type:** `number` **Default:** `undefined` An optional default time-to-live expiration period for session values, in seconds. By default, session values persist until they are deleted or the session is destroyed, and do not automatically expire because a particular amount of time has passed. Set `session.ttl` to add a default expiration period for your session values. Passing a `ttl` option to `session.set()` will override the global default for that individual entry. { session: { ttl: 60 * 60, // 1 hour } } Once you have configured a driver, you can use the `session` object to interact with the session. The object is accessible as `Astro.session` in your Astro components and pages and on the `context` object in API endpoints, middleware and actions. The API is the same in all cases. The session is generated automatically when it is first used and can be regenerated at any time with `Astro.session.regenerate()` or destroyed with `Astro.session.destroy()`. In most cases, you will only need to use `Astro.session.get()` and `Astro.session.set()`. For other available methods, see the API section. ### Astro components and pages Section titled Astro components and pages In `.astro` components and pages, you can access the session object via the global `Astro` object. For example, to display the number of items in a shopping cart: ---export const prerender = false; // Not needed with 'server' outputconst cart = await Astro.session.get('cart');---<a href="/checkout">🛒 {cart?.length ?? 0} items</a> In API endpoints, the session object is available on the `context` object. For example, to add an item to a shopping cart: import type { APIContext } from 'astro';export async function POST(req: Request, context: APIContext) { const cart = await context.session.get('cart'); cart.push(req.body.item); await context.session.set('cart', cart); return Response.json(cart);} In actions, the session object is available on the `context` object. For example, to add an item to a shopping cart: import { defineAction } from 'astro:actions';import { z } from 'astro:schema';export const server = { addToCart: defineAction({ input: z.object({ productId: z.string() }), handler: async (input, context) => { const cart = await context.session.get('cart'); cart.push(input.productId); await context.session.set('cart', cart); return cart; }, }),}; In middleware, the session object is available on the `context` object. For example, to set the last visit time in the session: import { defineMiddleware } from 'astro:middleware';export const onRequest = defineMiddleware(async (context, next) => { context.session.set('lastVisit', new Date()); return next();}); ### Session data types Section titled Session data types By default session data is untyped, and you can store arbitrary data in any key. Values are serialized and deserialized using devalue, which is the same library used in content collections and actions. This means that supported types are the same, and include strings, numbers, `Date`, `Map`, `Set`, `URL`, arrays, and plain objects. You can optionally define TypeScript types for your session data by creating a `src/env.d.ts` file and adding a declaration for the `App.SessionData` type: declare namespace App { interface SessionData { user: { id: string; name: string; }; cart: string[]; }} This will allow you to access the session data with type-checking and auto-completion in your editor: ---const cart = await Astro.session.get('cart');// const cart: string[] | undefinedconst something = await Astro.session.get('something');// const something: anyAstro.session.set('user', { id: 1, name: 'Houston' });// Error: Argument of type '{ id: number; name: string }' is not assignable to parameter of type '{ id: string; name: string; }'.--- Sessions are automatically created when they are first accessed. The session object is available in all Astro contexts, including components, actions, and API endpoints. In components, it is accessed via the global `Astro` object, and in actions and API endpoints, it is available on the `context` object. The API is the same in all cases. **Type**: `(key: string) => Promise<any>` Returns the value of the given key in the session. If the key does not exist, it returns `undefined`. **Type**: `(key: string, value: any, options?: { ttl: number }) => void` Sets the value of the given key in the session. The value can be any serializable type. This method is synchronous and the value is immediately available for retrieval, but it is not saved to the backend until the end of the request. **Type**: `(id: string) => Promise<void>` **Added in:** `astro@5.6.0` New Loads a session by ID. In normal use a session is loaded automatically from the request cookie, but this method can be used to load a session from a different ID. This is useful if you are handling the session ID yourself, or if you want to keep track of a session without using cookies. ### `session.regenerate()` Section titled session.regenerate() **Type**: `() => void` Regenerates the session ID. Best practice is to call this when a user logs in or escalates their privileges, to prevent session fixation attacks. ### `session.destroy()` Section titled session.destroy() **Type**: `() => void` Destroys the session, deleting the cookie and the object from the backend. This should be called when a user logs out or their session is otherwise invalidated. ## Further reading Section titled Further reading For full details and to give feedback on this experimental API, see the Sessions RFC. --- ## Page: https://docs.astro.build/en/reference/experimental-flags/serialized-configuration/ **Type:** `boolean` **Default:** `false` **Added in:** `astro@5.2.0` This feature allows access to the `astro:config` virtual module which exposes a non-exhaustive, serializable, type-safe version of the Astro configuration through two sub-modules. For a complete overview, and to give feedback on this experimental API, see the Serialized Manifest RFC. To enable this virtual module, add the `experimental.serializeConfig` feature flag to your Astro config: import { defineConfig } from "astro/config"export default defineConfig({ experimental: { serializeConfig: true }}) Then, configuration values can be used by any file in your Astro project: import { trailingSlash } from "astro:config/client";function addForwardSlash(path) { if (trailingSlash === "always") { return path.endsWith("/") ? path : path + "/" } else { return path }} The virtual module exposes two submodules for accessing different subsets of your configuration values. This protects your information by only making some data available to the client. All available config values can be accessed from `astro:config/server`. However, for code executed on the client, only those values exposed by `astro:config/client` will be available. ### `astro:config/client` Section titled astro:config/client The client submodule allows you to access a subset of the configuration values in `astro:config/server` that are safe to expose to the browser such as `trailingSlash`, `build.format`, `i18n`, and more. Use this submodule for client side code that is executed on the client. This is a developing feature. For a full, up-to-date list of the configuration values available from `astro:config/client`, please see the proposed API from the feature RFC ### `astro:config/server` Section titled astro:config/server The server submodule allows you to access a non-exhaustive set of your configuration values from `astro.config.mjs`. This includes `astro:config/client` values such as `trailingSlash` and `i18n`, but also more sensitive information about your file system configuration that is not safe to expose to the client such as `srcDir`, `cacheDir`, `outDir`. Attempting to use them on the client will raise an error. This is a developing feature. For a full, up-to-date list of the configuration values available from `astro:config/server`, please see the proposed API from the feature RFC. Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/experimental-flags/preserve-scripts-order/ **Type:** `boolean` **Default:** `false` **Added in:** `astro@5.5.0` Renders multiple `<style>` and `<script>` tags in the same order as they were declared in the source code. To enable this behavior, add the `experimental.preserveScriptOrder` feature flag to your Astro config: import { defineConfig } from "astro/config"export default defineConfig({ experimental: { preserveScriptOrder: true }}) This experimental flag requires no specific usage and only affects the order in which Astro renders your styles and scripts. When rendering multiple `<style>` and `<script>` tags on the same page, Astro currently reverses their order in your generated HTML output. This can give unexpected results, for example, CSS styles being overridden by earlier defined style tags when your site is built. This experimental flag instead renders `<script>` and `<style>` tags in the order they are defined. For example, the following component has two `<style>` tags and two `<script>` tags: <p>I am a component</p><style> body { background: red; }</style><style> body { background: yellow; }</style><script> console.log("hello")</script><script> console.log("world!")</script> After compiling, Astro’s default behavior will create an inline style where `yellow` appears first, and then `red`. This means the `red` background is applied. Similarly with the two scripts, the word `world!` is logged first, and then `hello` second: body {background:#ff0} body {background:red} console.log("world!")console.log("hello") When `experimental.preserveScriptOrder` is set to `true`, the rendering order of `<style>` and `<script>` tags matches the order in which they are written. For the same example component, the style generated `red` appears first, and then `yellow`; as for the scripts, `hello` is logged first, and then `world!`: body {background:red} body {background:#ff0} console.log("hello")console.log("world!") In a future major version, Astro will preserve style and script order by default, but you can opt in to the future behavior early using the `experimental.preserveScriptOrder` flag. Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/experimental-flags/heading-id-compat/ **Type:** `boolean` **Default:** `false` **Added in:** `astro@5.5.0` The `experimental.headingIdCompat` flag makes the IDs generated by Astro for Markdown headings compatible with common platforms like GitHub and npm. To enable heading ID compatibility, set the flag to `true` in your Astro configuration: import { defineConfig } from "astro/config"export default defineConfig({ experimental: { headingIdCompat: true, }}) This experimental flag allows you to retain the trailing hyphens on the end of IDs for Markdown headings ending in special characters, creating IDs compatible with those generated by other common platforms. It requires no specific usage and only affects how Astro generates the `id` for your headings written using Markdown syntax. Astro, like many platforms, uses the popular `github-slugger` package to convert the text content of a Markdown heading to a slug to use in IDs. This experimental flag allows you to omit Astro’s additional default processing step that strips a trailing hyphen from the end of IDs for headings ending in special characters. For example, the following Markdown heading: ## `<Picture />` will generate the following HTML in Astro by default: <h2 id="picture"><code><Picture /></h2> Using `experimental.headingIdCompat`, the same Markdown will generate the following HTML, which is identical to that of platforms such as GitHub: <h2 id="picture-"><code><Picture /></h2> In a future major version, Astro will switch to use the compatible ID style by default, but you can opt in to the future behavior early using the `experimental.headingIdCompat` flag. ## Usage with `rehypeHeadingIds` plugin Section titled Usage with rehypeHeadingIds plugin If you are using the `rehypeHeadingIds` plugin directly, opt in to the compatibility mode when passing the plugin in your Astro configuration: import { defineConfig } from 'astro/config';import { rehypeHeadingIds } from '@astrojs/markdown-remark';import { otherPluginThatReliesOnHeadingIDs } from 'some/plugin/source';export default defineConfig({ markdown: { rehypePlugins: [ [rehypeHeadingIds, { headingIdCompat: true }], otherPluginThatReliesOnHeadingIDs, ], },}); Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/legacy-flags/ To help some users migrate between versions of Astro, we occasionally introduce `legacy` flags. These flags allow you to opt in to some deprecated or otherwise outdated behavior of Astro in the latest version, so that you can continue to upgrade and take advantage of new Astro releases until you are able to fully update your project code. **Type:** `boolean` **Default:** `false` **Added in:** `astro@5.0.0` Enable legacy behavior for content collections (as used in Astro v2 through v4) import { defineConfig } from 'astro/config';export default defineConfig({ legacy: { collections: true }}); If enabled, `data` and `content` collections (only) are handled using the legacy content collections implementation. Collections with a `loader` (only) will continue to use the Content Layer API instead. Both kinds of collections may exist in the same project, each using their respective implementations. The following limitations continue to exist: * Any legacy (`type: 'content'` or `type: 'data'`) collections must continue to be located in the `src/content/` directory. * These legacy collections will not be transformed to implicitly use the `glob()` loader, and will instead be handled by legacy code. * Collections using the Content Layer API (with a `loader` defined) are forbidden in `src/content/`, but may exist anywhere else in your project. When you are ready to remove this flag and migrate to the new Content Layer API for your legacy collections, you must define a collection for any directories in `src/content/` that you want to continue to use as a collection. It is sufficient to declare an empty collection, and Astro will implicitly generate an appropriate definition for your legacy collections: import { defineCollection, z } from 'astro:content';const blog = defineCollection({ })export const collections = { blog }; Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/error-reference/ The following reference is a complete list of the errors you may encounter while using Astro. For additional assistance, including common pitfalls, please also see our Troubleshooting Guide. * **CantUseAstroConfigModuleError** Cannot use the `astro:config` module without enabling the experimental feature. * **UnknownCompilerError** Unknown compiler error. * **ClientAddressNotAvailable** `Astro.clientAddress` is not available in current adapter. * **PrerenderClientAddressNotAvailable** `Astro.clientAddress` cannot be used inside prerendered routes. * **StaticClientAddressNotAvailable** `Astro.clientAddress` is not available in prerendered pages. * **NoMatchingStaticPathFound** No static path found for requested path. * **OnlyResponseCanBeReturned** Invalid type returned by Astro page. * **MissingMediaQueryDirective** Missing value for `client:media` directive. * **NoMatchingRenderer** No matching renderer found. * **NoClientEntrypoint** No client entrypoint specified in renderer. * **NoClientOnlyHint** Missing hint on `client:only` directive. * **InvalidGetStaticPathParam** Invalid value returned by a `getStaticPaths` path. * **InvalidGetStaticPathsEntry** Invalid entry inside getStaticPath’s return value * **InvalidGetStaticPathsReturn** Invalid value returned by getStaticPaths. * **GetStaticPathsExpectedParams** Missing params property on `getStaticPaths` route. * **GetStaticPathsInvalidRouteParam** Invalid value for `getStaticPaths` route parameter. * **GetStaticPathsRequired** `getStaticPaths()` function required for dynamic routes. * **ReservedSlotName** Invalid slot name. * **NoAdapterInstalled** Cannot use Server-side Rendering without an adapter. * **AdapterSupportOutputMismatch** Adapter does not support server output. * **NoAdapterInstalledServerIslands** Cannot use Server Islands without an adapter. * **NoMatchingImport** No import found for component. * **InvalidPrerenderExport** Invalid prerender export. * **InvalidComponentArgs** Invalid component arguments. * **PageNumberParamNotFound** Page number param not found. * **ImageMissingAlt** Image missing required “alt” property. * **InvalidImageService** Error while loading image service. * **MissingImageDimension** Missing image dimensions * **FailedToFetchRemoteImageDimensions** Failed to retrieve remote image dimensions * **UnsupportedImageFormat** Unsupported image format * **UnsupportedImageConversion** Unsupported image conversion * **PrerenderDynamicEndpointPathCollide** Prerendered dynamic endpoint has path collision. * **ExpectedImage** Expected src to be an image. * **ExpectedImageOptions** Expected image options. * **ExpectedNotESMImage** Expected image options, not an ESM-imported image. * **IncompatibleDescriptorOptions** Cannot set both `densities` and `widths` * **ImageNotFound** Image not found. * **NoImageMetadata** Could not process image metadata. * **CouldNotTransformImage** Could not transform image. * **ResponseSentError** Unable to set response. * **MiddlewareNoDataOrNextCalled** The middleware didn’t return a `Response`. * **MiddlewareNotAResponse** The middleware returned something that is not a `Response` object. * **EndpointDidNotReturnAResponse** The endpoint did not return a `Response`. * **LocalsNotAnObject** Value assigned to `locals` is not accepted. * **LocalsReassigned** `locals` must not be reassigned. * **AstroResponseHeadersReassigned** `Astro.response.headers` must not be reassigned. * **MiddlewareCantBeLoaded** Can’t load the middleware. * **LocalImageUsedWrongly** Local images must be imported. * **AstroGlobUsedOutside** Astro.glob() used outside of an Astro file. * **AstroGlobNoMatch** Astro.glob() did not match any files. * **RedirectWithNoLocation** A redirect must be given a location with the `Location` header. * **UnsupportedExternalRedirect** Unsupported or malformed URL. * **InvalidDynamicRoute** Invalid dynamic route. * **MissingSharp** Could not find Sharp. * **UnknownViteError** Unknown Vite Error. * **FailedToLoadModuleSSR** Could not import file. * **InvalidGlob** Invalid glob pattern. * **FailedToFindPageMapSSR** Astro couldn’t find the correct page to render * **MissingLocale** The provided locale does not exist. * **MissingIndexForInternationalization** Index page not found. * **IncorrectStrategyForI18n** You can’t use the current function with the current strategy * **NoPrerenderedRoutesWithDomains** Prerendered routes aren’t supported when internationalization domains are enabled. * **MissingMiddlewareForInternationalization** Enabled manual internationalization routing without having a middleware. * **CantRenderPage** Astro can’t render the route. * **UnhandledRejection** Unhandled rejection * **i18nNotEnabled** i18n Not Enabled * **i18nNoLocaleFoundInPath** The path doesn’t contain any locale * **RouteNotFound** Route not found. * **EnvInvalidVariables** Invalid Environment Variables * **ServerOnlyModule** Module is only available server-side * **RewriteWithBodyUsed** Cannot use Astro.rewrite after the request body has been read * **ForbiddenRewrite** Forbidden rewrite to a static route. * **UnknownFilesystemError** An unknown error occurred while reading or writing files to disk. * **UnknownCSSError** Unknown CSS Error. * **CSSSyntaxError** CSS Syntax Error. ## Markdown Errors Section titled Markdown Errors * **UnknownMarkdownError** Unknown Markdown Error. * **MarkdownFrontmatterParseError** Failed to parse Markdown frontmatter. * **InvalidFrontmatterInjectionError** Invalid frontmatter injection. * **MdxIntegrationMissingError** MDX integration missing. * **UnknownConfigError** Unknown configuration error. * **ConfigNotFound** Specified configuration file not found. * **ConfigLegacyKey** Legacy configuration detected. * **UnknownCLIError** Unknown CLI Error. * **GenerateContentTypesError** Failed to generate content types. ## Content Collection Errors Section titled Content Collection Errors * **UnknownContentCollectionError** Unknown Content Collection Error. * **RenderUndefinedEntryError** Attempted to render an undefined content collection entry. * **GetEntryDeprecationError** Invalid use of `getDataEntryById` or `getEntryBySlug` function. * **InvalidContentEntryFrontmatterError** Content entry frontmatter does not match schema. * **InvalidContentEntryDataError** Content entry data does not match schema. * **ContentLoaderReturnsInvalidId** Content loader returned an entry with an invalid `id`. * **ContentEntryDataError** Content entry data does not match schema. * **ContentLoaderInvalidDataError** Content entry is missing an ID * **InvalidContentEntrySlugError** Invalid content entry slug. * **ContentSchemaContainsSlugError** Content Schema should not contain `slug`. * **MixedContentDataCollectionError** Content and data cannot be in same collection. * **ContentCollectionTypeMismatchError** Collection contains entries of a different type. * **DataCollectionEntryParseError** Data collection entry failed to parse. * **DuplicateContentEntrySlugError** Duplicate content entry slug. * **UnsupportedConfigTransformError** Unsupported transform in content config. * **ActionsWithoutServerOutputError** Actions must be used with server output. * **ActionsReturnedInvalidDataError** Action handler returned invalid data. * **ActionNotFoundError** Action not found. * **ActionCalledFromServerError** Action unexpected called from the server. * **ActionsCantBeLoaded** Can’t load the Astro actions. * **SessionWithoutSupportedAdapterOutputError** Sessions cannot be used with an adapter that doesn’t support server output. * **SessionStorageInitError** Session storage could not be initialized. * **SessionStorageSaveError** Session data could not be saved. * **SessionConfigMissingError** Session storage was enabled but not configured. * **SessionConfigWithoutFlagError** Session flag not set --- ## Page: https://docs.astro.build/en/reference/publish-to-npm/ Building a new Astro component? **Publish it to npm!** Publishing an Astro component is a great way to reuse your existing work across your projects, and to share with the wider Astro community at large. Astro components can be published directly to and installed from NPM, just like any other JavaScript package. Looking for inspiration? Check out some of our favorite themes and components from the Astro community. You can also search npm to see the entire public catalog. To get started developing your component quickly, you can use a template already set up for you. # Initialize the Astro Component template in a new directorynpm create astro@latest my-new-component-directory -- --template component# yarnyarn create astro my-new-component-directory --template component# pnpmpnpm create astro@latest my-new-component-directory -- --template component ## Creating a package Section titled Creating a package To create a new package, configure your development environment to use **workspaces** within your project. This will allow you to develop your component alongside a working copy of Astro. * Directorymy-new-component-directory/ * Directorydemo/ * … * package.json * Directorypackages/ * Directorymy-component/ * index.js * package.json * … This example, named `my-project`, creates a project with a single package, named `my-component`, and a `demo/` directory for testing and demonstrating the component. This is configured in the project root’s `package.json` file: { "name": "my-project", "workspaces": ["demo", "packages/*"]} In this example, multiple packages can be developed together from the `packages` directory. These packages can also be referenced from `demo`, where you can install a working copy of Astro. npm create astro@latest demo -- --template minimal# yarnyarn create astro demo --template minimal# pnpmpnpm create astro@latest demo -- --template minimal There are two initial files that will make up your individual package: `package.json` and `index.js`. The `package.json` in the package directory includes all of the information related to your package, including its description, dependencies, and any other package metadata. { "name": "my-component", "description": "Component description", "version": "1.0.0", "homepage": "https://github.com/owner/project#readme", "type": "module", "exports": { ".": "./index.js", "./astro": "./MyAstroComponent.astro", "./react": "./MyReactComponent.jsx" }, "files": ["index.js", "MyAstroComponent.astro", "MyReactComponent.jsx"], "keywords": ["astro", "withastro", "astro-component", "...", "..."]} A short description of your component used to help others know what it does. { "description": "An Astro Element Generator"} The module format used by Node.js and Astro to interpret your `index.js` files. { "type": "module"} Use `"type": "module"` so that your `index.js` can be used as an entrypoint with `import` and `export` . The url to the project homepage. { "homepage": "https://github.com/owner/project#readme"} This is a great way to direct users to an online demo, documentation, or homepage for your project. The entry points of a package when imported by name. { "exports": { ".": "./index.js", "./astro": "./MyAstroComponent.astro", "./react": "./MyReactComponent.jsx" }} In this example, importing `my-component` would use `index.js`, while importing `my-component/astro` or `my-component/react` would use `MyAstroComponent.astro` or `MyReactComponent.jsx` respectively. An optional optimization to exclude unnecessary files from the bundle shipped to users via npm. Note that **only files listed here will be included in your package**, so if you add or change files necessary for your package to work, you must update this list accordingly. { "files": ["index.js", "MyAstroComponent.astro", "MyReactComponent.jsx"]} An array of keywords relevant to your component, used to help others find your component on npm and in any other search catalogs. Add `astro-component` or `withastro` as a special keyword to maximize its discoverability in the Astro ecosystem. { "keywords": ["astro-component", "withastro", "... etc", "... etc"]} * * * The main **package entrypoint** used whenever your package is imported. export { default as MyAstroComponent } from './MyAstroComponent.astro';export { default as MyReactComponent } from './MyReactComponent.jsx'; This allows you to package multiple components together into a single interface. #### Example: Using Named Imports Section titled Example: Using Named Imports ---import { MyAstroComponent } from 'my-component';import { MyReactComponent } from 'my-component';---<MyAstroComponent /><MyReactComponent /> #### Example: Using Namespace Imports Section titled Example: Using Namespace Imports ---import * as Example from 'example-astro-component';---<Example.MyAstroComponent /><Example.MyReactComponent /> #### Example: Using Individual Imports Section titled Example: Using Individual Imports ---import MyAstroComponent from 'example-astro-component/astro';import MyReactComponent from 'example-astro-component/react';---<MyAstroComponent /><MyReactComponent /> * * * ## Developing your package Section titled Developing your package Astro does not have a dedicated “package mode” for development. Instead, you should use a demo project to develop and test your package inside of your project. This can be a private website only used for development, or a public demo/documentation website for your package. If you are extracting components from an existing project, you can even continue to use that project to develop your now-extracted components. ## Testing your component Section titled Testing your component Astro does not currently ship a test runner. _(If you are interested in helping out with this, join us on Discord!)_ In the meantime, our current recommendation for testing is: 1. Add a test `fixtures` directory to your `demo/src/pages` directory. 2. Add a new page for every test that you’d like to run. 3. Each page should include some different component usage that you’d like to test. 4. Run `astro build` to build your fixtures, then compare the output of the `dist/__fixtures__/` directory to what you expected. * Directorymy-project/demo/src/pages/\_\_fixtures\_\_/ * test-name-01.astro * test-name-02.astro * test-name-03.astro ## Publishing your component Section titled Publishing your component Once you have your package ready, you can publish it to npm using the `npm publish` command. If that fails, make sure that you have logged in via `npm login` and that your `package.json` is correct. If it succeeds, you’re done! Notice that there was no `build` step for Astro packages. Any file type that Astro supports natively, such as `.astro`, `.ts`, `.jsx`, and `.css`, can be published directly without a build step. If you need another file type that isn’t natively supported by Astro, add a build step to your package. This advanced exercise is left up to you. ## Integrations Library Section titled Integrations Library Share your hard work by adding your integration to our integrations library! ### `package.json` data Section titled package.json data The library is automatically updated weekly, pulling in every package published to NPM with the `astro-component` or `withastro` keyword. The integrations library reads the `name`, `description`, `repository`, and `homepage` data from your `package.json`. Avatars are a great way to highlight your brand in the library! Once your package is published you can file a GitHub issue with your avatar attached and we will add it to your listing. In addition to the required `astro-component` or `withastro` keyword, special keywords are also used to automatically organize packages. Including any of the keywords below will add your integration to the matching category in our integrations library. | category | keywords | | --- | --- | | Accessibility | `a11y`, `accessibility` | | Adapters | `astro-adapter` | | Analytics | `analytics` | | CSS + UI | `css`, `ui`, `icon`, `icons`, `renderer` | | Frameworks | `renderer` | | Content Loaders | `astro-loader` | | Images + Media | `media`, `image`, `images`, `video`, `audio` | | Performance + SEO | `performance`, `perf`, `seo`, `optimization` | | Dev Toolbar | `devtools`, `dev-overlay`, `dev-toolbar` | | Utilities | `tooling`, `utils`, `utility` | Packages that don’t include any keyword matching a category will be shown as `Uncategorized`. We encourage you to share your work, and we really do love seeing what our talented Astronauts create. Come and share what you create with us in our Discord or mention @astrodotbuild in a Tweet! --- ## Page: https://docs.astro.build/en/reference/errors/cant-use-astro-config-module-error/ > **CantUseAstroConfigModuleError**: Cannot import the module “MODULE\_NAME” because the experimental feature is disabled. Enable `experimental.serializeConfig` in your `astro.config.mjs` ## What went wrong? Section titled What went wrong? Cannot use the module `astro:config` without enabling the experimental feature. --- ## Page: https://docs.astro.build/en/reference/errors/unknown-compiler-error/ > Unknown compiler error. ## What went wrong? Section titled What went wrong? Astro encountered an unknown error while compiling your files. In most cases, this is not your fault, but an issue in our compiler. If there isn’t one already, please create an issue. **See Also:** * withastro/compiler issues list --- ## Page: https://docs.astro.build/en/reference/errors/client-address-not-available/ > **ClientAddressNotAvailable**: `Astro.clientAddress` is not available in the `ADAPTER_NAME` adapter. File an issue with the adapter to add support. ## What went wrong? Section titled What went wrong? The adapter you’re using unfortunately does not support `Astro.clientAddress`. **See Also:** * Official integrations * Astro.clientAddress Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/errors/prerender-client-address-not-available/ > **PrerenderClientAddressNotAvailable**: `Astro.clientAddress` cannot be used inside prerendered route NAME ## What went wrong? Section titled What went wrong? The `Astro.clientAddress` property cannot be used inside prerendered routes. **See Also:** * On-demand rendering * Astro.clientAddress Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/errors/static-client-address-not-available/ > **StaticClientAddressNotAvailable**: `Astro.clientAddress` is only available on pages that are server-rendered. ## What went wrong? Section titled What went wrong? The `Astro.clientAddress` property is only available when Server-side rendering is enabled. To get the user’s IP address in static mode, different APIs such as Ipify can be used in a Client-side script or it may be possible to get the user’s IP using a serverless function hosted on your hosting provider. **See Also:** * Enabling SSR in Your Project * Astro.clientAddress --- ## Page: https://docs.astro.build/en/reference/errors/no-matching-static-path-found/ > **NoMatchingStaticPathFound**: A `getStaticPaths()` route pattern was matched, but no matching static path was found for requested path `PATH_NAME`. ## What went wrong? Section titled What went wrong? A dynamic route was matched, but no corresponding path was found for the requested parameters. This is often caused by a typo in either the generated or the requested path. **See Also:** * getStaticPaths() --- ## Page: https://docs.astro.build/en/reference/errors/only-response-can-be-returned/ > Route returned a `RETURNED_VALUE`. Only a Response can be returned from Astro files. ## What went wrong? Section titled What went wrong? Only instances of Response can be returned inside Astro files. pages/login.astro ---return new Response(null, { status: 404, statusText: 'Not found'});// Alternatively, for redirects, Astro.redirect also returns an instance of Responsereturn Astro.redirect('/login');--- **See Also:** * Response Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/errors/missing-media-query-directive/ > **MissingMediaQueryDirective**: Media query not provided for `client:media` directive. A media query similar to `client:media="(max-width: 600px)"` must be provided ## What went wrong? Section titled What went wrong? A media query parameter is required when using the `client:media` directive. <Counter client:media="(max-width: 640px)" /> **See Also:** * `client:media` Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/errors/no-matching-renderer/ > Unable to render `COMPONENT_NAME`. There are `RENDERER_COUNT` renderer(s) configured in your `astro.config.mjs` file, but none were able to server-side render `COMPONENT_NAME`. ## What went wrong? Section titled What went wrong? None of the installed integrations were able to render the component you imported. Make sure to install the appropriate integration for the type of component you are trying to include in your page. For JSX / TSX files, @astrojs/react, @astrojs/preact or @astrojs/solid-js can be used. For Vue and Svelte files, the @astrojs/vue and @astrojs/svelte integrations can be used respectively **See Also:** * Frameworks components * UI Frameworks --- ## Page: https://docs.astro.build/en/reference/errors/no-client-entrypoint/ > **NoClientEntrypoint**: `COMPONENT_NAME` component has a `client:CLIENT_DIRECTIVE` directive, but no client entrypoint was provided by `RENDERER_NAME`. ## What went wrong? Section titled What went wrong? Astro tried to hydrate a component on the client, but the renderer used does not provide a client entrypoint to use to hydrate. **See Also:** * addRenderer option * Hydrating framework components --- ## Page: https://docs.astro.build/en/reference/errors/no-client-only-hint/ > **NoClientOnlyHint**: Unable to render `COMPONENT_NAME`. When using the `client:only` hydration strategy, Astro needs a hint to use the correct renderer. ## What went wrong? Section titled What went wrong? `client:only` components are not run on the server, as such Astro does not know (and cannot guess) which renderer to use and require a hint. Like such: <SomeReactComponent client:only="react" /> **See Also:** * `client:only` --- ## Page: https://docs.astro.build/en/reference/errors/invalid-get-static-path-param/ > **InvalidGetStaticPathParam**: Invalid params given to `getStaticPaths` path. Expected an `object`, got `PARAM_TYPE` ## What went wrong? Section titled What went wrong? The `params` property in `getStaticPaths`’s return value (an array of objects) should also be an object. pages/blog/\[id\].astro ---export async function getStaticPaths() { return [ { params: { slug: "blog" } }, { params: { slug: "about" } } ];}--- **See Also:** * `getStaticPaths()` * `params` --- ## Page: https://docs.astro.build/en/reference/errors/invalid-get-static-paths-entry/ > **InvalidGetStaticPathsEntry**: Invalid entry returned by getStaticPaths. Expected an object, got `ENTRY_TYPE` ## What went wrong? Section titled What went wrong? `getStaticPaths`’s return value must be an array of objects. In most cases, this error happens because an array of array was returned. Using `.flatMap()` or a `.flat()` call may be useful. export async function getStaticPaths() { return [ // <-- Array { params: { slug: "blog" } }, // <-- Object { params: { slug: "about" } } ];} **See Also:** * `getStaticPaths()` --- ## Page: https://docs.astro.build/en/reference/errors/invalid-get-static-paths-return/ > **InvalidGetStaticPathsReturn**: Invalid type returned by `getStaticPaths`. Expected an `array`, got `RETURN_TYPE` ## What went wrong? Section titled What went wrong? `getStaticPaths`’s return value must be an array of objects. pages/blog/\[id\].astro export async function getStaticPaths() { return [ // <-- Array { params: { slug: "blog" } }, { params: { slug: "about" } } ];} **See Also:** * `getStaticPaths()` * `params` Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/errors/get-static-paths-expected-params/ > **GetStaticPathsExpectedParams**: Missing or empty required `params` property on `getStaticPaths` route. ## What went wrong? Section titled What went wrong? Every route specified by `getStaticPaths` require a `params` property specifying the path parameters needed to match the route. For instance, the following code: pages/blog/\[id\].astro ---export async function getStaticPaths() { return [ { params: { id: '1' } } ];}--- Will create the following route: `site.com/blog/1`. **See Also:** * `getStaticPaths()` * `params` --- ## Page: https://docs.astro.build/en/reference/errors/get-static-paths-invalid-route-param/ > **GetStaticPathsInvalidRouteParam**: Invalid getStaticPaths route parameter for `KEY`. Expected undefined, a string or a number, received `VALUE_TYPE` (`VALUE`) ## What went wrong? Section titled What went wrong? Since `params` are encoded into the URL, only certain types are supported as values. ---export async function getStaticPaths() { return [ { params: { id: '1' } } // Works { params: { id: 2 } } // Works { params: { id: false } } // Does not work ];}--- In routes using rest parameters, `undefined` can be used to represent a path with no parameters passed in the URL: ---export async function getStaticPaths() { return [ { params: { id: 1 } } // /route/1 { params: { id: 2 } } // /route/2 { params: { id: undefined } } // /route/ ];}--- **See Also:** * `getStaticPaths()` * `params` --- ## Page: https://docs.astro.build/en/reference/errors/get-static-paths-required/ > **GetStaticPathsRequired**: `getStaticPaths()` function is required for dynamic routes. Make sure that you `export` a `getStaticPaths` function from your dynamic route. ## What went wrong? Section titled What went wrong? In Static Mode, all routes must be determined at build time. As such, dynamic routes must `export` a `getStaticPaths` function returning the different paths to generate. **See Also:** * Dynamic Routes * `getStaticPaths()` * Server-side Rendering --- ## Page: https://docs.astro.build/en/reference/errors/reserved-slot-name/ > **ReservedSlotName**: Unable to create a slot named `SLOT_NAME`. `SLOT_NAME` is a reserved slot name. Please update the name of this slot. ## What went wrong? Section titled What went wrong? Certain words cannot be used for slot names due to being already used internally. **See Also:** * Named slots --- ## Page: https://docs.astro.build/en/reference/errors/no-adapter-installed/ > **NoAdapterInstalled**: Cannot use server-rendered pages without an adapter. Please install and configure the appropriate server adapter for your final deployment. ## What went wrong? Section titled What went wrong? To use server-side rendering, an adapter needs to be installed so Astro knows how to generate the proper output for your targeted deployment platform. **See Also:** * Server-side Rendering --- ## Page: https://docs.astro.build/en/reference/errors/adapter-support-output-mismatch/ > **AdapterSupportOutputMismatch**: The `ADAPTER_NAME` adapter is configured to output a static website, but the project contains server-rendered pages. Please install and configure the appropriate server adapter for your final deployment. ## What went wrong? Section titled What went wrong? The currently configured adapter does not support server-side rendering, which is required for the current project setup. Depending on your adapter, there may be a different entrypoint to use for server-side rendering. For example, the `@astrojs/vercel` adapter has a `@astrojs/vercel/static` entrypoint for static rendering, and a `@astrojs/vercel/serverless` entrypoint for server-side rendering. **See Also:** * Server-side Rendering --- ## Page: https://docs.astro.build/en/reference/errors/no-adapter-installed-server-islands/ > **NoAdapterInstalledServerIslands**: Cannot use server islands without an adapter. Please install and configure the appropriate server adapter for your final deployment. ## What went wrong? Section titled What went wrong? To use server islands, the same constraints exist as for sever-side rendering, so an adapter is needed. **See Also:** * On-demand Rendering --- ## Page: https://docs.astro.build/en/reference/errors/no-matching-import/ > **NoMatchingImport**: Could not render `COMPONENT_NAME`. No matching import has been found for `COMPONENT_NAME`. ## What went wrong? Section titled What went wrong? No import statement was found for one of the components. If there is an import statement, make sure you are using the same identifier in both the imports and the component usage. --- ## Page: https://docs.astro.build/en/reference/errors/invalid-prerender-export/ > **Example error messages:** > InvalidPrerenderExport: A `prerender` export has been detected, but its value cannot be statically analyzed. ## What went wrong? Section titled What went wrong? The `prerender` feature only supports a subset of valid JavaScript — be sure to use exactly `export const prerender = true` so that our compiler can detect this directive at build time. Variables, `let`, and `var` declarations are not supported. --- ## Page: https://docs.astro.build/en/reference/errors/invalid-component-args/ > **Example error messages:** > InvalidComponentArgs: Invalid arguments passed to `<MyAstroComponent>` component. ## What went wrong? Section titled What went wrong? Astro components cannot be rendered manually via a function call, such as `Component()` or `{items.map(Component)}`. Prefer the component syntax `<Component />` or `{items.map(item => <Component {...item} />)}`. --- ## Page: https://docs.astro.build/en/reference/errors/page-number-param-not-found/ > **PageNumberParamNotFound**: \[paginate()\] page number param `PARAM_NAME` not found in your filepath. ## What went wrong? Section titled What went wrong? The page number parameter was not found in your filepath. **See Also:** * Pagination --- ## Page: https://docs.astro.build/en/reference/errors/image-missing-alt/ > **ImageMissingAlt**: Image missing “alt” property. “alt” text is required to describe important images on the page. ## What went wrong? Section titled What went wrong? The `alt` property allows you to provide descriptive alt text to users of screen readers and other assistive technologies. In order to ensure your images are accessible, the `Image` component requires that an `alt` be specified. If the image is merely decorative (i.e. doesn’t contribute to the understanding of the page), set `alt=""` so that screen readers know to ignore the image. **See Also:** * Images * Image component * Image component#alt --- ## Page: https://docs.astro.build/en/reference/errors/invalid-image-service/ > **InvalidImageService**: There was an error loading the configured image service. Please see the stack trace for more information. ## What went wrong? Section titled What went wrong? There was an error while loading the configured image service. This can be caused by various factors, such as your image service not properly exporting a compatible object in its default export, or an incorrect path. If you believe that your service is properly configured and this error is wrong, please open an issue. **See Also:** * Image Service API --- ## Page: https://docs.astro.build/en/reference/errors/missing-image-dimension/ > Missing width and height attributes for `IMAGE_URL`. When using remote images, both dimensions are required in order to avoid cumulative layout shift (CLS). ## What went wrong? Section titled What went wrong? For remote images, `width` and `height` cannot automatically be inferred from the original file. To avoid cumulative layout shift (CLS), either specify these two properties, or set `inferSize` to `true` to fetch a remote image’s original dimensions. If your image is inside your `src` folder, you probably meant to import it instead. See the Imports guide for more information. **See Also:** * Images * Image component#width-and-height-required --- ## Page: https://docs.astro.build/en/reference/errors/failed-to-fetch-remote-image-dimensions/ > Failed to get the dimensions for `IMAGE_URL`. ## What went wrong? Section titled What went wrong? Determining the remote image’s dimensions failed. This is typically caused by an incorrect URL or attempting to infer the size of an image in the public folder which is not possible. --- ## Page: https://docs.astro.build/en/reference/errors/unsupported-image-format/ > **UnsupportedImageFormat**: Received unsupported format `FORMAT` from `IMAGE_PATH`. Currently only SUPPORTED\_FORMATS.JOIN(’, ’) are supported by our image services. ## What went wrong? Section titled What went wrong? The built-in image services do not currently support optimizing all image formats. For unsupported formats such as GIFs, you may be able to use an `img` tag directly: ---import rocket from '../assets/images/rocket.gif';---<img src={rocket.src} width={rocket.width} height={rocket.height} alt="A rocketship in space." /> --- ## Page: https://docs.astro.build/en/reference/errors/unsupported-image-conversion/ > **UnsupportedImageConversion**: Converting between vector (such as SVGs) and raster (such as PNGs and JPEGs) images is not currently supported. ## What went wrong? Section titled What went wrong? Astro does not currently supporting converting between vector (such as SVGs) and raster (such as PNGs and JPEGs) images. **See Also:** * Images --- ## Page: https://docs.astro.build/en/reference/errors/prerender-dynamic-endpoint-path-collide/ > **PrerenderDynamicEndpointPathCollide**: Could not render `PATHNAME` with an `undefined` param as the generated path will collide during prerendering. Prevent passing `undefined` as `params` for the endpoint’s `getStaticPaths()` function, or add an additional extension to the endpoint’s filename. ## What went wrong? Section titled What went wrong? The endpoint is prerendered with an `undefined` param so the generated path will collide with another route. If you cannot prevent passing `undefined`, then an additional extension can be added to the endpoint file name to generate the file with a different name. For example, renaming `pages/api/[slug].ts` to `pages/api/[slug].json.ts`. **See Also:** * `getStaticPaths()` * `params` --- ## Page: https://docs.astro.build/en/reference/errors/expected-image/ > **ExpectedImage**: Expected `src` property for `getImage` or `<Image />` to be either an ESM imported image or a string with the path of a remote image. Received `SRC` (type: `TYPEOF_OPTIONS`). > > Full serialized options received: `FULL_OPTIONS`. ## What went wrong? Section titled What went wrong? An image’s `src` property is not valid. The Image component requires the `src` attribute to be either an image that has been ESM imported or a string. This is also true for the first parameter of `getImage()`. ---import { Image } from "astro:assets";import myImage from "../assets/my_image.png";---<Image src={myImage} alt="..." /><Image src="https://example.com/logo.png" width={300} height={300} alt="..." /> In most cases, this error happens when the value passed to `src` is undefined. **See Also:** * Images --- ## Page: https://docs.astro.build/en/reference/errors/expected-image-options/ > **ExpectedImageOptions**: Expected getImage() parameter to be an object. Received `OPTIONS`. ## What went wrong? Section titled What went wrong? `getImage()`’s first parameter should be an object with the different properties to apply to your image. import { getImage } from "astro:assets";import myImage from "../assets/my_image.png";const optimizedImage = await getImage({src: myImage, width: 300, height: 300}); In most cases, this error happens because parameters were passed directly instead of inside an object. **See Also:** * Images --- ## Page: https://docs.astro.build/en/reference/errors/expected-not-esmimage/ > **ExpectedNotESMImage**: An ESM-imported image cannot be passed directly to `getImage()`. Instead, pass an object with the image in the `src` property. ## What went wrong? Section titled What went wrong? An ESM-imported image cannot be passed directly to `getImage()`. Instead, pass an object with the image in the `src` property. import { getImage } from "astro:assets";import myImage from "../assets/my_image.png"; const optimizedImage = await getImage( myImage ); const optimizedImage = await getImage({ src: myImage }); **See Also:** * Images --- ## Page: https://docs.astro.build/en/reference/errors/incompatible-descriptor-options/ > **IncompatibleDescriptorOptions**: Only one of `densities` or `widths` can be specified. In most cases, you’ll probably want to use only `widths` if you require specific widths. ## What went wrong? Section titled What went wrong? Only one of `densities` or `widths` can be specified. Those attributes are used to construct a `srcset` attribute, which cannot have both `x` and `w` descriptors. **See Also:** * Images --- ## Page: https://docs.astro.build/en/reference/errors/image-not-found/ > **ImageNotFound**: Could not find requested image `IMAGE_PATH`. Does it exist? ## What went wrong? Section titled What went wrong? Astro could not find an image you imported. Often, this is simply caused by a typo in the path. Images in Markdown are relative to the current file. To refer to an image that is located in the same folder as the `.md` file, the path should start with `./` **See Also:** * Images --- ## Page: https://docs.astro.build/en/reference/errors/no-image-metadata/ > Could not process image metadata for `IMAGE_PATH`. ## What went wrong? Section titled What went wrong? Astro could not process the metadata of an image you imported. This is often caused by a corrupted or malformed image and re-exporting the image from your image editor may fix this issue. **See Also:** * Images --- ## Page: https://docs.astro.build/en/reference/errors/could-not-transform-image/ > **CouldNotTransformImage**: Could not transform image `IMAGE_PATH`. See the stack trace for more information. ## What went wrong? Section titled What went wrong? Astro could not transform one of your images. Often, this is caused by a corrupted or malformed image. Re-exporting the image from your image editor may fix this issue. Depending on the image service you are using, the stack trace may contain more information on the specific error encountered. **See Also:** * Images --- ## Page: https://docs.astro.build/en/reference/errors/response-sent-error/ > **ResponseSentError**: The response has already been sent to the browser and cannot be altered. ## What went wrong? Section titled What went wrong? Making changes to the response, such as setting headers, cookies, and the status code cannot be done outside of page components. --- ## Page: https://docs.astro.build/en/reference/errors/middleware-no-data-or-next-called/ > **MiddlewareNoDataOrNextCalled**: Make sure your middleware returns a `Response` object, either directly or by returning the `Response` from calling the `next` function. ## What went wrong? Section titled What went wrong? Thrown when the middleware does not return any data or call the `next` function. For example: import {defineMiddleware} from "astro:middleware";export const onRequest = defineMiddleware((context, _) => { // doesn't return anything or call `next` context.locals.someData = false;}); Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/errors/middleware-not-aresponse/ > **MiddlewareNotAResponse**: Any data returned from middleware must be a valid `Response` object. ## What went wrong? Section titled What went wrong? Thrown in development mode when middleware returns something that is not a `Response` object. For example: import {defineMiddleware} from "astro:middleware";export const onRequest = defineMiddleware(() => { return "string"}); Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/errors/endpoint-did-not-return-aresponse/ > **EndpointDidNotReturnAResponse**: An endpoint must return either a `Response`, or a `Promise` that resolves with a `Response`. ## What went wrong? Section titled What went wrong? Thrown when an endpoint does not return anything or returns an object that is not a `Response` object. An endpoint must return either a `Response`, or a `Promise` that resolves with a `Response`. For example: import type { APIContext } from 'astro';export async function GET({ request, url, cookies }: APIContext): Promise<Response> { return Response.json({ success: true, result: 'Data from Astro Endpoint!' })} --- ## Page: https://docs.astro.build/en/reference/errors/locals-not-an-object/ > **LocalsNotAnObject**: `locals` can only be assigned to an object. Other values like numbers, strings, etc. are not accepted. ## What went wrong? Section titled What went wrong? Thrown when `locals` is overwritten with something that is not an object For example: import {defineMiddleware} from "astro:middleware";export const onRequest = defineMiddleware((context, next) => { context.locals = 1541; return next();}); --- ## Page: https://docs.astro.build/en/reference/errors/locals-reassigned/ > **LocalsReassigned**: `locals` can not be assigned directly. ## What went wrong? Section titled What went wrong? Thrown when a value is being set as the `locals` field on the Astro global or context. --- ## Page: https://docs.astro.build/en/reference/errors/astro-response-headers-reassigned/ > **AstroResponseHeadersReassigned**: Individual headers can be added to and removed from `Astro.response.headers`, but it must not be replaced with another instance of `Headers` altogether. ## What went wrong? Section titled What went wrong? Thrown when a value is being set as the `headers` field on the `ResponseInit` object available as `Astro.response`. --- ## Page: https://docs.astro.build/en/reference/errors/middleware-cant-be-loaded/ > **MiddlewareCantBeLoaded**: An unknown error was thrown while loading your middleware. ## What went wrong? Section titled What went wrong? Thrown in development mode when middleware throws an error while attempting to loading it. For example: import {defineMiddleware} from "astro:middleware";throw new Error("Error thrown while loading the middleware.")export const onRequest = defineMiddleware(() => { return "string"}); Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/errors/local-image-used-wrongly/ > **LocalImageUsedWrongly**: `Image`’s and `getImage`’s `src` parameter must be an imported image or an URL, it cannot be a string filepath. Received `IMAGE_FILE_PATH`. ## What went wrong? Section titled What went wrong? When using the default image services, `Image`’s and `getImage`’s `src` parameter must be either an imported image or an URL, it cannot be a string of a filepath. For local images from content collections, you can use the image() schema helper to resolve the images. ---import { Image } from "astro:assets";import myImage from "../my_image.png";---<!-- GOOD: `src` is the full imported image. --><Image src={myImage} alt="Cool image" /><!-- GOOD: `src` is a URL. --><Image src="https://example.com/my_image.png" alt="Cool image" /><!-- BAD: `src` is an image's `src` path instead of the full image object. --><Image src={myImage.src} alt="Cool image" /><!-- BAD: `src` is a string filepath. --><Image src="../my_image.png" alt="Cool image" /> **See Also:** * Images --- ## Page: https://docs.astro.build/en/reference/errors/astro-glob-used-outside/ > **AstroGlobUsedOutside**: `Astro.glob(GLOB_STR)` can only be used in `.astro` files. `import.meta.glob(GLOB_STR)` can be used instead to achieve a similar result. ## What went wrong? Section titled What went wrong? `Astro.glob()` can only be used in `.astro` files. You can use `import.meta.glob()` instead to achieve the same result. **See Also:** * Astro.glob --- ## Page: https://docs.astro.build/en/reference/errors/astro-glob-no-match/ > **AstroGlobNoMatch**: `Astro.glob(GLOB_STR)` did not return any matching files. ## What went wrong? Section titled What went wrong? `Astro.glob()` did not return any matching files. There might be a typo in the glob pattern. **See Also:** * Astro.glob --- ## Page: https://docs.astro.build/en/reference/errors/redirect-with-no-location/ ## What went wrong? Section titled What went wrong? A redirect must be given a location with the `Location` header. **See Also:** * Astro.redirect Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/errors/unsupported-external-redirect/ > **UnsupportedExternalRedirect**: An external redirect must start with http or https, and must be a valid URL. ## What went wrong? Section titled What went wrong? An external redirect must start with http or https, and must be a valid URL. **See Also:** * Astro.redirect --- ## Page: https://docs.astro.build/en/reference/errors/invalid-dynamic-route/ > **InvalidDynamicRoute**: The INVALID\_PARAM param for route ROUTE is invalid. Received **RECEIVED**. ## What went wrong? Section titled What went wrong? A dynamic route param is invalid. This is often caused by an `undefined` parameter or a missing rest parameter. **See Also:** * Dynamic routes --- ## Page: https://docs.astro.build/en/reference/errors/missing-sharp/ > **MissingSharp**: Could not find Sharp. Please install Sharp (`sharp`) manually into your project or migrate to another image service. ## What went wrong? Section titled What went wrong? Sharp is the default image service used for `astro:assets`. When using a strict package manager like pnpm, Sharp must be installed manually into your project in order to use image processing. If you are not using `astro:assets` for image processing, and do not wish to install Sharp, you can configure the following passthrough image service that does no processing: import { defineConfig, passthroughImageService } from "astro/config";export default defineConfig({ image: { service: passthroughImageService(), },}); **See Also:** * Default Image Service * Image Services API --- ## Page: https://docs.astro.build/en/reference/errors/unknown-vite-error/ ## What went wrong? Section titled What went wrong? Vite encountered an unknown error while rendering your project. We unfortunately do not know what happened (or we would tell you!) If you can reliably cause this error to happen, we’d appreciate if you could open an issue **See Also:** * Vite troubleshooting guide --- ## Page: https://docs.astro.build/en/reference/errors/failed-to-load-module-ssr/ > **FailedToLoadModuleSSR**: Could not import `IMPORT_NAME`. ## What went wrong? Section titled What went wrong? Astro could not import the requested file. Oftentimes, this is caused by the import path being wrong (either because the file does not exist, or there is a typo in the path) This message can also appear when a type is imported without specifying that it is a type import. **See Also:** * Type Imports --- ## Page: https://docs.astro.build/en/reference/errors/invalid-glob/ > **InvalidGlob**: Invalid glob pattern: `GLOB_PATTERN`. Glob patterns must start with ’./’, ‘../’ or ’/‘. ## What went wrong? Section titled What went wrong? Astro encountered an invalid glob pattern. This is often caused by the glob pattern not being a valid file path. **See Also:** * Glob Patterns --- ## Page: https://docs.astro.build/en/reference/errors/failed-to-find-page-map-ssr/ > **FailedToFindPageMapSSR**: Astro couldn’t find the correct page to render, probably because it wasn’t correctly mapped for SSR usage. This is an internal error. Please file an issue. ## What went wrong? Section titled What went wrong? Astro couldn’t find the correct page to render, probably because it wasn’t correctly mapped for SSR usage. This is an internal error. --- ## Page: https://docs.astro.build/en/reference/errors/missing-locale/ > **MissingLocale**: The locale/path `LOCALE` does not exist in the configured `i18n.locales`. ## What went wrong? Section titled What went wrong? Astro can’t find the requested locale. All supported locales must be configured in i18n.locales and have corresponding directories within `src/pages/`. --- ## Page: https://docs.astro.build/en/reference/errors/missing-index-for-internationalization/ > **MissingIndexForInternationalization**: Could not find index page. A root index page is required in order to create a redirect to the index URL of the default locale. (`/DEFAULT_LOCALE`) ## What went wrong? Section titled What went wrong? Astro could not find the index URL of your website. An index page is required so that Astro can create a redirect from the main index page to the localized index page of the default locale when using `i18n.routing.prefixDefaultLocale`. **See Also:** * Internationalization * `i18n.routing` Configuration Reference --- ## Page: https://docs.astro.build/en/reference/errors/incorrect-strategy-for-i18n/ > **IncorrectStrategyForI18n**: The function `FUNCTION_NAME` can only be used when the `i18n.routing.strategy` is set to `"manual"`. ## What went wrong? Section titled What went wrong? Some internationalization functions are only available when Astro’s own i18n routing is disabled by the configuration setting `i18n.routing: "manual"`. **See Also:** * `i18n` routing --- ## Page: https://docs.astro.build/en/reference/errors/no-prerendered-routes-with-domains/ > **NoPrerenderedRoutesWithDomains**: Static pages aren’t yet supported with multiple domains. To enable this feature, you must disable prerendering for the page COMPONENT ## What went wrong? Section titled What went wrong? Static pages aren’t yet supported with i18n domains. If you wish to enable this feature, you have to disable prerendering. --- ## Page: https://docs.astro.build/en/reference/errors/missing-middleware-for-internationalization/ > **MissingMiddlewareForInternationalization**: Your configuration setting `i18n.routing: 'manual'` requires you to provide your own i18n `middleware` file. ## What went wrong? Section titled What went wrong? Astro throws an error if the user enables manual routing, but it doesn’t have a middleware file. --- ## Page: https://docs.astro.build/en/reference/errors/cant-render-page/ > **CantRenderPage**: Astro cannot find any content to render for this route. There is no file or redirect associated with this route. ## What went wrong? Section titled What went wrong? Astro could not find an associated file with content while trying to render the route. This is an Astro error and not a user error. If restarting the dev server does not fix the problem, please file an issue. --- ## Page: https://docs.astro.build/en/reference/errors/unhandled-rejection/ > **UnhandledRejection**: Astro detected an unhandled rejection. Here’s the stack trace: > STACK ## What went wrong? Section titled What went wrong? Astro could not find any code to handle a rejected `Promise`. Make sure all your promises have an `await` or `.catch()` handler. --- ## Page: https://docs.astro.build/en/reference/errors/i18n-not-enabled/ > **i18nNotEnabled**: The `astro:i18n` module can not be used without enabling i18n in your Astro config. ## What went wrong? Section titled What went wrong? The `astro:i18n` module can not be used without enabling i18n in your Astro config. To enable i18n, add a default locale and a list of supported locales to your Astro config: import { defineConfig } from 'astro'export default defineConfig({ i18n: { locales: ['en', 'fr'], defaultLocale: 'en', },}) For more information on internationalization support in Astro, see our Internationalization guide. **See Also:** * Internationalization * `i18n` Configuration Reference --- ## Page: https://docs.astro.build/en/reference/errors/i18n-no-locale-found-in-path/ > **i18nNoLocaleFoundInPath**: You tried to use an i18n utility on a path that doesn’t contain any locale. You can use `pathHasLocale` first to determine if the path has a locale. ## What went wrong? Section titled What went wrong? An i18n utility tried to use the locale from a URL path that does not contain one. You can prevent this error by using pathHasLocale to check URLs for a locale first before using i18n utilities. --- ## Page: https://docs.astro.build/en/reference/errors/route-not-found/ > **RouteNotFound**: Astro could not find a route that matches the one you requested. ## What went wrong? Section titled What went wrong? Astro couldn’t find a route matching the one provided by the user --- ## Page: https://docs.astro.build/en/reference/errors/env-invalid-variables/ > The following environment variables defined in `env.schema` are invalid. ## What went wrong? Section titled What went wrong? Some environment variables do not match the data type and/or properties defined in `env.schema`. --- ## Page: https://docs.astro.build/en/reference/errors/server-only-module/ > **ServerOnlyModule**: The “NAME” module is only available server-side. ## What went wrong? Section titled What went wrong? This module is only available server-side. --- ## Page: https://docs.astro.build/en/reference/errors/rewrite-with-body-used/ > **RewriteWithBodyUsed**: Astro.rewrite() cannot be used if the request body has already been read. If you need to read the body, first clone the request. ## What went wrong? Section titled What went wrong? `Astro.rewrite()` cannot be used if the request body has already been read. If you need to read the body, first clone the request. For example: const data = await Astro.request.clone().formData();Astro.rewrite("/target") **See Also:** * Request.clone() * Astro.rewrite --- ## Page: https://docs.astro.build/en/reference/errors/forbidden-rewrite/ > **ForbiddenRewrite**: You tried to rewrite the on-demand route ‘FROM’ with the static route ‘TO’, when using the ‘server’ output. > > The static route ‘TO’ is rendered by the component ‘COMPONENT’, which is marked as prerendered. This is a forbidden operation because during the build the component ‘COMPONENT’ is compiled to an HTML file, which can’t be retrieved at runtime by Astro. ## What went wrong? Section titled What went wrong? `Astro.rewrite()` can’t be used to rewrite an on-demand route with a static route when using the `"server"` output. --- ## Page: https://docs.astro.build/en/reference/errors/unknown-filesystem-error/ ## What went wrong? Section titled What went wrong? An unknown error occurred while reading or writing files to disk. It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. --- ## Page: https://docs.astro.build/en/reference/errors/unknown-csserror/ ## What went wrong? Section titled What went wrong? Astro encountered an unknown error while parsing your CSS. Oftentimes, this is caused by a syntax error and the error message should contain more information. **See Also:** * Styles and CSS --- ## Page: https://docs.astro.build/en/reference/errors/csssyntax-error/ > **Example error messages:** > CSSSyntaxError: Missed semicolon > CSSSyntaxError: Unclosed string ## What went wrong? Section titled What went wrong? Astro encountered an error while parsing your CSS, due to a syntax error. This is often caused by a missing semicolon. --- ## Page: https://docs.astro.build/en/reference/errors/unknown-markdown-error/ ## What went wrong? Section titled What went wrong? Astro encountered an unknown error while parsing your Markdown. Oftentimes, this is caused by a syntax error and the error message should contain more information. --- ## Page: https://docs.astro.build/en/reference/errors/markdown-frontmatter-parse-error/ > **Example error messages:** > can not read an implicit mapping pair; a colon is missed > unexpected end of the stream within a double quoted scalar > can not read a block mapping entry; a multiline key may not be an implicit key ## What went wrong? Section titled What went wrong? Astro encountered an error while parsing the frontmatter of your Markdown file. This is often caused by a mistake in the syntax, such as a missing colon or a missing end quote. --- ## Page: https://docs.astro.build/en/reference/errors/invalid-frontmatter-injection-error/ > **InvalidFrontmatterInjectionError**: A remark or rehype plugin attempted to inject invalid frontmatter. Ensure “astro.frontmatter” is set to a valid JSON object that is not `null` or `undefined`. ## What went wrong? Section titled What went wrong? A remark or rehype plugin attempted to inject invalid frontmatter. This occurs when “astro.frontmatter” is set to `null`, `undefined`, or an invalid JSON object. **See Also:** * Modifying frontmatter programmatically --- ## Page: https://docs.astro.build/en/reference/errors/mdx-integration-missing-error/ > **MdxIntegrationMissingError**: Unable to render FILE. Ensure that the `@astrojs/mdx` integration is installed. ## What went wrong? Section titled What went wrong? Unable to find the official `@astrojs/mdx` integration. This error is raised when using MDX files without an MDX integration installed. **See Also:** * MDX installation and usage --- ## Page: https://docs.astro.build/en/reference/errors/unknown-config-error/ ## What went wrong? Section titled What went wrong? Astro encountered an unknown error loading your Astro configuration file. This is often caused by a syntax error in your config and the message should offer more information. If you can reliably cause this error to happen, we’d appreciate if you could open an issue **See Also:** * Configuration Reference --- ## Page: https://docs.astro.build/en/reference/errors/config-not-found/ > **ConfigNotFound**: Unable to resolve `--config "CONFIG_FILE"`. Does the file exist? ## What went wrong? Section titled What went wrong? The specified configuration file using `--config` could not be found. Make sure that it exists or that the path is correct **See Also:** * \--config --- ## Page: https://docs.astro.build/en/reference/errors/config-legacy-key/ > **ConfigLegacyKey**: Legacy configuration detected: `LEGACY_CONFIG_KEY`. ## What went wrong? Section titled What went wrong? Astro detected a legacy configuration option in your configuration file. **See Also:** * Configuration reference Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/errors/unknown-clierror/ ## What went wrong? Section titled What went wrong? Astro encountered an unknown error while starting one of its CLI commands. The error message should contain more information. If you can reliably cause this error to happen, we’d appreciate if you could open an issue --- ## Page: https://docs.astro.build/en/reference/errors/generate-content-types-error/ > **GenerateContentTypesError**: `astro sync` command failed to generate content collection types: ERROR\_MESSAGE ## What went wrong? Section titled What went wrong? `astro sync` command failed to generate content collection types. **See Also:** * Content collections documentation Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/errors/unknown-content-collection-error/ ## What went wrong? Section titled What went wrong? Astro encountered an unknown error loading your content collections. This can be caused by certain errors inside your `src/content.config.ts` file or some internal errors. If you can reliably cause this error to happen, we’d appreciate if you could open an issue --- ## Page: https://docs.astro.build/en/reference/errors/render-undefined-entry-error/ ## What went wrong? Section titled What went wrong? Astro tried to render a content collection entry that was undefined. This can happen if you try to render an entry that does not exist. --- ## Page: https://docs.astro.build/en/reference/errors/get-entry-deprecation-error/ > **GetEntryDeprecationError**: The `METHOD` function is deprecated and cannot be used to query the “COLLECTION” collection. Use `getEntry` instead. ## What went wrong? Section titled What went wrong? The `getDataEntryById` and `getEntryBySlug` functions are deprecated and cannot be used with content layer collections. Use the `getEntry` function instead. --- ## Page: https://docs.astro.build/en/reference/errors/invalid-content-entry-frontmatter-error/ > **Example error message:** > **blog** → **post.md** frontmatter does not match collection schema. > “title” is required. > “date” must be a valid date. ## What went wrong? Section titled What went wrong? A Markdown or MDX entry does not match its collection schema. Make sure that all required fields are present, and that all fields are of the correct type. You can check against the collection schema in your `src/content.config.*` file. See the Content collections documentation for more information. --- ## Page: https://docs.astro.build/en/reference/errors/invalid-content-entry-data-error/ > **Example error message:** > **blog** → **post** frontmatter does not match collection schema. > “title” is required. > “date” must be a valid date. ## What went wrong? Section titled What went wrong? A content entry does not match its collection schema. Make sure that all required fields are present, and that all fields are of the correct type. You can check against the collection schema in your `src/content.config.*` file. See the Content collections documentation for more information. --- ## Page: https://docs.astro.build/en/reference/errors/content-loader-returns-invalid-id/ > **Example error message:** > The content loader for the collection **blog** returned an entry with an invalid `id`: > { > “id”: 1, > “title”: “Hello, World!” > } ## What went wrong? Section titled What went wrong? A content loader returned an invalid `id`. Make sure that the `id` of the entry is a string. See the Content collections documentation for more information. --- ## Page: https://docs.astro.build/en/reference/errors/content-entry-data-error/ > **Example error message:** > **blog** → **post** data does not match collection schema. > “title” is required. > “date” must be a valid date. ## What went wrong? Section titled What went wrong? A content entry does not match its collection schema. Make sure that all required fields are present, and that all fields are of the correct type. You can check against the collection schema in your `src/content.config.*` file. See the Content collections documentation for more information. --- ## Page: https://docs.astro.build/en/reference/errors/content-loader-invalid-data-error/ > **Example error message:** > The loader for **blog** returned invalid data. > Object is missing required property “id”. ## What went wrong? Section titled What went wrong? The loader for a content collection returned invalid data. Inline loaders must return an array of objects with unique ID fields or a plain object with IDs as keys and entries as values. --- ## Page: https://docs.astro.build/en/reference/errors/invalid-content-entry-slug-error/ > `COLLECTION_NAME` → `ENTRY_ID` has an invalid slug. `slug` must be a string. ## What went wrong? Section titled What went wrong? A collection entry has an invalid `slug`. This field is reserved for generating entry slugs, and must be a string when present. **See Also:** * The reserved entry `slug` field --- ## Page: https://docs.astro.build/en/reference/errors/content-schema-contains-slug-error/ > **ContentSchemaContainsSlugError**: A content collection schema should not contain `slug` since it is reserved for slug generation. Remove this from your COLLECTION\_NAME collection schema. ## What went wrong? Section titled What went wrong? A legacy content collection schema should not contain the `slug` field. This is reserved by Astro for generating entry slugs. Remove `slug` from your schema. You can still use custom slugs in your frontmatter. **See Also:** * Legacy content collections --- ## Page: https://docs.astro.build/en/reference/errors/mixed-content-data-collection-error/ > **MixedContentDataCollectionError**: **COLLECTION\_NAME** contains a mix of content and data entries. All entries must be of the same type. ## What went wrong? Section titled What went wrong? A legacy content collection cannot contain a mix of content and data entries. You must store entries in separate collections by type. **See Also:** * Legacy content collections --- ## Page: https://docs.astro.build/en/reference/errors/content-collection-type-mismatch-error/ > **ContentCollectionTypeMismatchError**: COLLECTION contains EXPECTED\_TYPE entries, but is configured as a ACTUAL\_TYPE collection. ## What went wrong? Section titled What went wrong? Legacy content collections must contain entries of the type configured. Collections are `type: 'content'` by default. Try adding `type: 'data'` to your collection config for data collections. **See Also:** * Legacy content collections --- ## Page: https://docs.astro.build/en/reference/errors/data-collection-entry-parse-error/ > `COLLECTION_ENTRY_NAME` failed to parse. ## What went wrong? Section titled What went wrong? Collection entries of `type: 'data'` must return an object with valid JSON (for `.json` entries) or YAML (for `.yaml` entries). --- ## Page: https://docs.astro.build/en/reference/errors/duplicate-content-entry-slug-error/ > `COLLECTION_NAME` contains multiple entries with the same slug: `SLUG`. Slugs must be unique. ## What went wrong? Section titled What went wrong? Content collection entries must have unique slugs. Duplicates are often caused by the `slug` frontmatter property. --- ## Page: https://docs.astro.build/en/reference/errors/unsupported-config-transform-error/ > **UnsupportedConfigTransformError**: `transform()` functions in your content config must return valid JSON, or data types compatible with the devalue library (including Dates, Maps, and Sets). > Full error: PARSE\_ERROR ## What went wrong? Section titled What went wrong? `transform()` functions in your content config must return valid JSON, or data types compatible with the devalue library (including Dates, Maps, and Sets). **See Also:** * devalue library --- ## Page: https://docs.astro.build/en/reference/errors/actions-without-server-output-error/ > **ActionsWithoutServerOutputError**: A server is required to create callable backend functions. To deploy routes to a server, add an adapter to your Astro config and configure your route for on-demand rendering ## What went wrong? Section titled What went wrong? Your project must have a server output to create backend functions with Actions. **See Also:** * On-demand rendering --- ## Page: https://docs.astro.build/en/reference/errors/actions-returned-invalid-data-error/ > **ActionsReturnedInvalidDataError**: Action handler returned invalid data. Handlers should return serializable data types like objects, arrays, strings, and numbers. Parse error: ERROR ## What went wrong? Section titled What went wrong? Action handler returned invalid data. Handlers should return serializable data types, and cannot return a Response object. **See Also:** * Actions handler reference --- ## Page: https://docs.astro.build/en/reference/errors/action-not-found-error/ > **ActionNotFoundError**: The server received a request for an action named `ACTION_NAME` but could not find a match. If you renamed an action, check that you’ve updated your `actions/index` file and your calling code to match. ## What went wrong? Section titled What went wrong? The server received a request for an action but could not find a match with the same name. --- ## Page: https://docs.astro.build/en/reference/errors/action-called-from-server-error/ > **ActionCalledFromServerError**: Action called from a server page or endpoint without using `Astro.callAction()`. This wrapper must be used to call actions from server code. ## What went wrong? Section titled What went wrong? Action called from a server page or endpoint without using `Astro.callAction()`. **See Also:** * `Astro.callAction()` reference --- ## Page: https://docs.astro.build/en/reference/errors/actions-cant-be-loaded/ > **ActionsCantBeLoaded**: An unknown error was thrown while loading the Astro actions file. ## What went wrong? Section titled What went wrong? Thrown in development mode when the actions file can’t be loaded. --- ## Page: https://docs.astro.build/en/reference/errors/session-without-supported-adapter-output-error/ > **SessionWithoutSupportedAdapterOutputError**: Sessions require an adapter that supports server output. The adapter must set `"server"` in the `buildOutput` adapter feature. ## What went wrong? Section titled What went wrong? Your adapter must support server output to use sessions. **See Also:** * Server output adapter feature --- ## Page: https://docs.astro.build/en/reference/errors/session-storage-init-error/ > Error when initializing session storage with driver `DRIVER`. `ERROR` ## What went wrong? Section titled What went wrong? Thrown when the session storage could not be initialized. **See Also:** * experimental.session Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/errors/session-storage-save-error/ > Error when saving session data with driver `DRIVER`. `ERROR` ## What went wrong? Section titled What went wrong? Thrown when the session data could not be saved. **See Also:** * experimental.session Contribute Community Sponsor --- ## Page: https://docs.astro.build/en/reference/errors/session-config-missing-error/ > The `experimental.session` flag was set to `true`, but no storage was configured. Either configure the storage manually or use an adapter that provides session storage ## What went wrong? Section titled What went wrong? Thrown when session storage is enabled but not configured. **See Also:** * experimental.session --- ## Page: https://docs.astro.build/en/reference/errors/session-config-without-flag-error/ > Session config was provided without enabling the `experimental.session` flag ## What went wrong? Section titled What went wrong? Thrown when session storage is configured but the `experimental.session` flag is not enabled. **See Also:** * experimental.session Contribute Community Sponsor