API Reference
Questi contenuti non sono ancora disponibili nella tua lingua.
Astro
global
Section titled Astro globalThe Astro
global is available in all contexts in .astro
files. It has the following functions:
Astro.glob()
Section titled Astro.glob()Astro.glob()
is a way to load many local files into your static site setup.
.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 troubleshooting guide for a workaround.) This is because Astro.glob()
is a wrapper of Vite’s import.meta.glob()
.
You can also use import.meta.glob()
itself in your Astro project. You may want to do this when:
- You need this feature in a file that isn’t
.astro
, like an API route.Astro.glob()
is only available in.astro
files, whileimport.meta.glob()
is available anywhere in the project. - You don’t want to load each file immediately.
import.meta.glob()
can return functions that import the file content, rather than returning the content itself. Note that this import includes all styles and scripts for any imported files. These will be bundled and added to the page whether or not a file is actually used, as this is decided by static analysis, not at runtime. - You want access to each file’s path.
import.meta.glob()
returns a map of a file’s path to its content, whileAstro.glob()
returns a list of content. - You want to pass multiple patterns; for example, you want to add a “negative pattern” that filters out certain files.
import.meta.glob()
can optionally take an array of glob strings, rather than a single string.
Read more in the Vite documentation.
Markdown Files
Section titled Markdown FilesMarkdown files loaded with Astro.glob()
return the following MarkdownInstance
interface:
You can optionally provide a type for the frontmatter
variable using a TypeScript generic.
Astro Files
Section titled Astro FilesAstro files have the following interface:
Other Files
Section titled Other FilesOther files may have various different interfaces, but Astro.glob()
accepts a TypeScript generic if you know exactly what an unrecognized file type contains.
Astro.props
Section titled Astro.propsAstro.props
is an object containing any values that have been passed as component attributes. Layout components for .md
and .mdx
files receive frontmatter values as props.
Astro.params
Section titled Astro.paramsAstro.params
is an object containing the values of dynamic route segments matched for this request.
In static builds, this will be the params
returned by getStaticPaths()
used for prerendering dynamic routes.
In SSR builds, this can be any value matching the path segments in the dynamic route pattern.
See also: params
Astro.request
Section titled Astro.requestType: Request
Astro.request
is a standard Request object. It can be used to get the url
, headers
, method
, and even body of the request.
See also: Astro.url
With the default output: 'static'
option, Astro.request.url
does not contain search parameters, like ?foo=bar
, as it’s not possible to determine them ahead of time during static builds. However in output: 'server'
mode, Astro.request.url
does contain search parameters as it can be determined from a server request.
Astro.response
Section titled Astro.responseType: ResponseInit & { readonly headers: Headers }
Astro.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
: AHeaders
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.
Or to set a header:
Astro.cookies
Section titled Astro.cookiesType: AstroCookies
astro@1.4.0
Astro.cookies
contains utilities for reading and manipulating cookies in server-side rendering mode.
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
.
delete
Section titled deleteType: (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
.
merge
Section titled mergeType: (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.
headers
Section titled headersType: () => Iterator<string>
Gets the header values for Set-Cookie
that will be sent out with the response.
AstroCookie
Section titled AstroCookieGetting a cookie via Astro.cookies.get()
returns a AstroCookie
type. It has the following structure.
value
Section titled valueType: 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.
number
Section titled numberType: () => number
Parses the cookie value as a Number. Returns NaN if not a valid number.
boolean
Section titled booleanType: () => boolean
Converts the cookie value to a boolean.
AstroCookieGetOptions
Section titled AstroCookieGetOptions
Aggiunto in:
astro@4.1.0
Getting a cookie also allows specifying options via the AstroCookieGetOptions
interface:
decode
Section titled decodeType: (value: string) => string
Allows customization of how a cookie is deserialized into a value.
AstroCookieSetOptions
Section titled AstroCookieSetOptions
Aggiunto in:
astro@4.1.0
Setting a cookie via Astro.cookies.set()
allows passing in a AstroCookieSetOptions
to customize how the cookie is serialized.
domain
Section titled domainType: string
Specifies the domain. If no domain is set, most clients will interpret to apply to the current domain.
expires
Section titled expiresType: Date
Specifies the date on which the cookie will expire.
httpOnly
Section titled httpOnlyType: boolean
If true, the cookie will not be accessible client-side.
maxAge
Section titled maxAgeType: 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.
sameSite
Section titled sameSiteType: boolean | 'lax' | 'none' | 'strict'
Specifies the value of the SameSite cookie header.
secure
Section titled secureType: boolean
If true, the cookie is only set on https sites.
encode
Section titled encodeType: (value: string) => string
Allows customizing how the cookie is serialized.
Astro.redirect()
Section titled Astro.redirect()Type: (path: string, status?: number) => Response
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 sites, this will produce a client redirect using a <meta http-equiv="refresh">
tag and does not support status codes.
When using an on-demand rendering mode, status codes are supported. Astro will serve redirected requests with a default HTTP response status of 302
unless another code is specified.
The following example redirects a user to a login page:
Astro.rewrite()
Section titled Astro.rewrite()Type: (rewritePayload: string | URL | Request) => Promise<Response>
astro@4.13.0
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:
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:
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.url
Section titled Astro.urlType: URL
astro@1.0.0-rc
A URL object constructed from the current Astro.request.url
URL string value. Useful for interacting with individual properties of the request URL, like pathname and origin.
Equivalent to doing new URL(Astro.request.url)
.
Astro.url
will be localhost
in dev mode if site is not configured for static sites, and for on-demand rendered sites using server
or hybrid
output.
You can also use Astro.url
to create new URLs by passing it as an argument to new URL()
.
Astro.clientAddress
Section titled Astro.clientAddressType: string
astro@1.0.0-rc
Specifies the IP address of the request. This property is only available when building for SSR (server-side rendering) and should not be used for static sites.
Astro.site
Section titled Astro.siteType: URL | undefined
Astro.site
returns a URL
made from site
in your Astro config. If site
in your Astro config isn’t defined, Astro.site
won’t be defined.
Astro.generator
Section titled Astro.generatorType: string
astro@1.0.0
Astro.generator
is a convenient way to add a <meta name="generator">
tag with your current version of Astro. It follows the format "Astro v1.x.x"
.
Astro.slots
Section titled Astro.slotsAstro.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.
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()
.
This is for advanced use cases! In most circumstances, it is simpler to render slot contents with the <slot />
element.
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:
A callback function passed as <Shout />
’s child will receive the all-caps message
parameter:
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.
Use a standard HTML element for the wrapping tag, or any lower case 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
Section titled Astro.selfAstro.self
allows Astro components to be recursively called. This behaviour lets you render an Astro component from within itself by using <Astro.self>
in the component template. This can be helpful for iterating over large data stores and nested data-structures.
This component could then be used like this:
And would render HTML like this:
Astro.locals
Section titled Astro.locals
Aggiunto in:
astro@2.4.0
Astro.locals
is an object containing any values from the context.locals
object from a middleware. Use this to access data returned by middleware in your .astro
files.
Astro.preferredLocale
Section titled Astro.preferredLocaleType: string | undefined
astro@3.5.0
Astro.preferredLocale
is a computed value that represents the preferred locale of the user.
It is computed by checking the configured locales in your i18n.locales
array and locales supported by the users’s browser via the header Accept-Language
. This value is undefined
if no such match exists.
This property is only available when building for SSR (server-side rendering) and should not be used for static sites.
Astro.preferredLocaleList
Section titled Astro.preferredLocaleListType: string[] | undefined
astro@3.5.0
Astro.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 []
: 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 when building for SSR (server-side rendering) and should not be used for static sites.
Astro.currentLocale
Section titled Astro.currentLocaleType: string | undefined
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
.
Astro.getActionResult()
Section titled Astro.getActionResult()Type: (action: TAction) => ActionReturnType<TAction> | undefined
astro@4.15.0
Beta
Astro.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
.
Astro.callAction()
Section titled Astro.callAction()
Aggiunto in:
astro@4.15.0
Beta
Astro.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.
Endpoint Context
Section titled Endpoint ContextEndpoint functions receive a context object as the first parameter. It mirrors many of the Astro
global properties.
context.params
Section titled context.paramscontext.params
is an object containing the values of dynamic route segments matched for this request.
In static builds, this will be the params
returned by getStaticPaths()
used for prerendering dynamic routes.
In SSR builds, this can be any value matching the path segments in the dynamic route pattern.
See also: params
context.props
Section titled context.props
Aggiunto in:
astro@1.5.0
context.props
is an object containing any props
passed from getStaticPaths()
. Because getStaticPaths()
is not used when building for SSR (server-side rendering), context.props
is only available in static builds.
See also: Data Passing with props
context.request
Section titled context.requestType: Request
A standard Request object. It can be used to get the url
, headers
, method
, and even body of the request.
See also: Astro.request
context.cookies
Section titled context.cookiesType: AstroCookies
context.cookies
contains utilities for reading and manipulating cookies.
See also: Astro.cookies
context.url
Section titled context.urlType: URL
astro@1.5.0
A URL object constructed from the current context.request.url
URL string value.
See also: Astro.url
context.clientAddress
Section titled context.clientAddressType: string
astro@1.5.0
Specifies the IP address of the request. This property is only available when building for SSR (server-side rendering) and should not be used for static sites.
See also: Astro.clientAddress
context.site
Section titled context.siteType: URL | undefined
astro@1.5.0
context.site
returns a URL
made from site
in your Astro config. If undefined, this will return a URL generated from localhost
.
See also: Astro.site
context.generator
Section titled context.generatorType: string
astro@1.5.0
context.generator
is a convenient way to indicate the version of Astro your project is running. It follows the format "Astro v1.x.x"
.
See also: Astro.generator
context.redirect()
Section titled context.redirect()Type: (path: string, status?: number) => Response
astro@1.5.0
context.redirect()
returns a Response object that allows you to redirect to another page. This function is only available when building for SSR (server-side rendering) and should not be used for static sites.
See also: Astro.redirect()
context.rewrite()
Section titled context.rewrite()Type: (rewritePayload: string | URL | Request) => Promise<Response>
astro@4.13.0
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:
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:
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:
See also: Astro.rewrite()
context.locals
Section titled context.locals
Aggiunto in:
astro@2.4.0
context.locals
is an object used to store and access arbitrary information during the lifecycle of a request.
Middleware functions can read and write the values of context.locals
:
API endpoints can only read information from context.locals
:
See also: Astro.locals
context.getActionResult()
Section titled context.getActionResult()Type: (action: TAction) => ActionReturnType<TAction> | undefined
astro@4.15.0
Beta
context.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
.
See also Astro.getActionResult()
context.callAction()
Section titled context.callAction()
Aggiunto in:
astro@4.15.0
Beta
context.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.
See also Astro.callAction()
Endpoint Context
Section titled Endpoint ContextEndpoint functions receive a context object as the first parameter. It mirrors many of the Astro
global properties.
getStaticPaths()
Section titled getStaticPaths()Type: (options: GetStaticPathsOptions) => Promise<GetStaticPathsResult> | GetStaticPathsResult
If a page uses dynamic params in the filename, that component will need to export a getStaticPaths()
function.
This function is required because Astro is a static site builder. That means that your entire site is built ahead of time. If Astro doesn’t know to generate a page at build time, your users won’t see it when they visit your site.
The getStaticPaths()
function should return an array of objects to determine which paths will be pre-rendered by Astro.
It can also be used in static file endpoints for dynamic routing.
The getStaticPaths()
function executes in its own isolated scope once, before any page loads. Therefore you can’t reference anything from its parent scope, other than file imports. The compiler will warn if you break this requirement.
params
Section titled paramsThe params
key of every returned object tells Astro what routes to build. The returned params must map back to the dynamic parameters and rest parameters defined in your component filepath.
params
are encoded into the URL, so only strings are supported as values. The value for each params
object must match the parameters used in the page name.
For example, suppose that you have a page at src/pages/posts/[id].astro
. If you export getStaticPaths
from this page and return the following for paths:
Then Astro will statically generate posts/1
, posts/2
, and posts/3
at build time.
Data Passing with props
Section titled Data Passing with propsTo pass additional data to each generated page, you can also set a props
value on every returned path object. Unlike params
, props
are not encoded into the URL and so aren’t limited to only strings.
For example, suppose that you generate pages based off of data fetched from a remote API. You can pass the full data object to the page component inside of getStaticPaths
:
You can also pass a regular array, which may be helpful when generating or stubbing a known list of routes.
Then Astro will statically generate posts/1
and posts/2
at build time using the page component in pages/posts/[id].astro
. The page can reference this data using Astro.props
:
paginate()
Section titled paginate()Pagination is a common use-case for websites that Astro natively supports via the paginate()
function. paginate()
will automatically generate the array to return from getStaticPaths()
that creates one URL for every page of the paginated collection. The page number will be passed as a param, and the page data will be passed as a page
prop.
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.
paginate()
has the following arguments:
pageSize
- The number of items shown per page (10
by default)params
- Send additional parameters for creating dynamic routesprops
- Send additional props to be available on each page
The pagination page
prop
Section titled The pagination page propPagination 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.
page.data
Section titled page.dataType: Array
Array of data returned from data()
for the current page.
page.start
Section titled page.startType: number
Index of first item on current page, starting at 0
. (e.g. if pageSize: 25
, this would be 0
on page 1, 25
on page 2, etc.)
page.end
Section titled page.endType: number
Index of last item on current page.
page.size
Section titled page.sizeType: number
Default: 10
How many items per-page.
page.total
Section titled page.totalType: number
The total number of items across all pages.
page.currentPage
Section titled page.currentPageType: number
The current page number, starting with 1
.
page.lastPage
Section titled page.lastPageType: number
The total number of pages.
page.url.current
Section titled page.url.currentType: string
Get the URL of the current page (useful for canonical URLs).
page.url.prev
Section titled page.url.prevType: 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.
page.url.next
Section titled page.url.nextType: 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.
page.url.first
Section titled page.url.firstType: string | undefined
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.
page.url.last
Section titled page.url.lastType: string | undefined
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.
import.meta
Section titled import.metaAll ESM modules include a import.meta
property. Astro adds import.meta.env
through Vite.
import.meta.env.SSR
can be used to know when rendering on the server. Sometimes you might want different logic, like a component that should only be rendered in the client:
Images (astro:assets
)
Section titled Images (astro:assets)getImage()
Section titled getImage()Type: (options: UnresolvedImageTransform) => Promise<GetImageResult>
getImage()
relies on server-only APIs and breaks the build when used on the client.
The getImage()
function is intended for generating images destined to be used somewhere else than directly in HTML, for example in an API Route. It also allows you to create your own custom <Image />
component.
getImage()
takes an options object with the same properties as the Image component (except alt
).
It returns an object with the following type:
Content Collections (astro:content
)
Section titled Content Collections (astro:content)
Aggiunto 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.
defineCollection()
Section titled defineCollection()Type: (input: CollectionConfig) => CollectionConfig
defineCollection()
is a utility to configure a collection in a src/content/config.*
file.
This function accepts the following properties:
Type: 'content' | 'data'
Default: 'content'
astro@2.5.0
type
is a string that defines the type of entries stored within a collection:
'content'
- for content-authoring formats like Markdown (.md
), MDX (.mdx
), or Markdoc (.mdoc
)'data'
- for data-only formats like JSON (.json
) or YAML (.yaml
)
This means collections cannot store a mix of content and data formats. You must split these entries into separate collections by type.
schema
Section titled schemaType: ZodType | (context: SchemaContext) => ZodType
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.
reference()
Section titled reference()Type: (collection: string) => ZodEffects<ZodString, { collection, id: string } | { collection, slug: string }>
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.
This example defines references from a blog author to the authors
collection and an array of related posts to the same blog
collection:
See the Content Collection
guide for example usage.
getCollection()
Section titled getCollection()Type: (collection: string, filter?: (entry: CollectionEntry<collection>) => boolean) => CollectionEntry<collection>[]
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
, slug
, or frontmatter values via the data
object.
See the Content Collection
guide for example usage.
getEntry()
Section titled getEntry()
Aggiunto in:
astro@2.5.0
Types:
(collection: string, contentSlugOrDataId: string) => CollectionEntry<collection>
({ collection: string, id: string }) => CollectionEntry<collection>
({ collection: string, slug: string }) => CollectionEntry<collection>
getEntry()
is a function that retrieves a single collection entry by collection name and either the entry id
(for type: 'data'
collections) or entry slug
(for type: 'content'
collections). getEntry()
can also be used to get referenced entries to access the data
, body
, or render()
properties:
See the Content Collections
guide for examples of querying collection entries.
getEntries()
Section titled getEntries()
Aggiunto in:
astro@2.5.0
Types:
(Array<{ collection: string, id: string }>) => Array<CollectionEntry<collection>>
(Array<{ collection: string, slug: string }>) => Array<CollectionEntry<collection>>
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
, body
, and render()
properties.
getEntryBySlug()
Section titled getEntryBySlug()Type: (collection: string, slug: string) => Promise<CollectionEntry<collection>>
Use the getEntry()
function to query content entries. This accepts the same arguments as getEntryBySlug()
, and supports querying by id
for JSON or YAML collections.
getEntryBySlug()
is a function that retrieves a single collection entry by collection name and entry slug
.
See the Content Collection
guide for example usage.
getDataEntryById()
Section titled getDataEntryById()Type: (collection: string, id: string) => Promise<CollectionEntry<collection>>
astro@2.5.0
Use the getEntry()
function to query data entries. This accepts the same arguments as getDataEntryById()
, and supports querying by slug
for content authoring formats like Markdown.
getDataEntryById()
is a function that retrieves a single collection entry by collection name and entry id
.
Collection Entry Type
Section titled Collection Entry TypeQuery functions including getCollection()
, getEntry()
, and getEntries()
each return entries with the CollectionEntry
type. This type is available as a utility from astro:content
:
The CollectionEntry<TCollectionName>
type is an object with the following values. TCollectionName
is the name of the collection you’re querying (e.g. CollectionEntry<'blog'>
).
Available for: type: 'content'
and type: 'data'
collections
Example Types:
- content collections:
'entry-1.md' | 'entry-2.md' | ...
- data collections:
'author-1' | 'author-2' | ...
A unique ID using the file path relative to src/content/[collection]
. Enumerates all possible string values based on the collection entry file paths. Note that collections defined as type: 'content'
include the file extension in their ID, while collections defined as type: 'data'
do not.
collection
Section titled collectionAvailable for: type: 'content'
and type: 'data'
collections
Example Type: 'blog' | 'authors' | ...
The name of a top-level folder under src/content/
in which entries are located. This is the name used to reference the collection in your schema, and in querying functions.
Available for: type: 'content'
and type: 'data'
collections
Type: CollectionSchema<TCollectionName>
An object of frontmatter properties inferred from your collection schema (see defineCollection()
reference). Defaults to any
if no schema is configured.
Available for: type: 'content'
collections only
Example Type: 'entry-1' | 'entry-2' | ...
A URL-ready slug for Markdown or MDX documents. Defaults to the id
without the file extension, but can be overridden by setting the slug
property in a file’s frontmatter.
Available for: type: 'content'
collections only
Type: string
A string containing the raw, uncompiled body of the Markdown or MDX document.
render()
Section titled render()Available for: type: 'content'
collections only
Type: () => Promise<RenderedEntry>
A function to compile a given Markdown or MDX document 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’sgetHeadings()
utility on Markdown and MDX imports.remarkPluginFrontmatter
- The modified frontmatter object after any remark or rehype plugins have been applied. Set to typeany
.
See the Content Collection
guide for example usage.
Other Content Collection Types
Section titled Other Content Collection TypesThe astro:content
module also exports the following types for use in your Astro project:
CollectionKey
Section titled CollectionKey
Aggiunto 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 that accepts any collection name.
ContentCollectionKey
Section titled ContentCollectionKey
Aggiunto in:
astro@3.1.0
A string union of all the names of type: 'content'
collections defined in your src/content/config.*
file.
DataCollectionKey
Section titled DataCollectionKey
Aggiunto in:
astro@3.1.0
A string union of all the names of type: 'data'
collection defined in your src/content/config.*
file.
SchemaContext
Section titled SchemaContextThe 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
- Theimage()
schema helper that allows you to use local images in Content Collections
Middleware (astro:middleware
)
Section titled Middleware (astro:middleware)
Aggiunto 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.
onRequest()
Section titled onRequest()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()
.
context
Section titled contextType: APIContext
The first argument of onRequest()
is a context object. It mirrors many of the Astro
global properties.
next()
Section titled next()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.
sequence()
Section titled sequence()Type: (...handlers: MiddlewareHandler[]) => MiddlewareHandler
A function that accepts middleware functions as arguments, and will execute them in the order in which they are passed.
createContext()
Section titled createContext()Type: (context: CreateContext) => APIContext
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
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.
Internationalization (astro:i18n
)
Section titled Internationalization (astro:i18n)
Aggiunto 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:
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.
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.
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.
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.
getLocaleByPath()
Section titled getLocaleByPath()Type: (path: string) => string
A function that returns the code
associated to a locale path
.
redirectToDefaultLocale()
Section titled redirectToDefaultLocale()Type: (context: APIContext, statusCode?: ValidRedirectStatus) => Promise<Response>
astro@4.6.0
Available only when i18n.routing
is set to "manual"
A function that returns a Response
that redirects to the defaultLocale
configured. It accepts an optional valid redirect status code.
redirectToFallback()
Section titled redirectToFallback()Type: (context: APIContext, response: Response) => Promise<Response>
astro@4.6.0
Available only when i18n.routing
is set to "manual"
A function that allows you to use your i18n.fallback
configuration in your own middleware.
notFound()
Section titled notFound()Type: (context: APIContext, response?: Response) => Promise<Response> | undefined
astro@4.6.0
Available only when i18n.routing
is set to "manual"
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.
middleware()
Section titled middleware()Type: (options: { prefixDefaultLocale: boolean, redirectToDefaultLocale: boolean }) => MiddlewareHandler
astro@4.6.0
Available only when i18n.routing
is set to "manual"
A function that allows you to programmatically create the Astro i18n middleware.
This is use useful when you still want to use the default i18n logic, but add only a few exceptions to your website.
requestHasLocale()
Section titled requestHasLocale()Type: (context: APIContext) => boolean
astro@4.6.0
Available only when i18n.routing
is set to "manual"
Checks whether the current URL contains a configured locale. Internally, this function will use APIContext#url.pathname
.
Actions (astro:actions )
Section titled Actions (astro:actions )
Aggiunto in:
astro@4.15.0
Beta
Actions are backend functions used for type-safe server-to-client communication. All utilities to define and call actions are exposed by the astro:actions
module. For examples and usage instructions, see the Actions guide.
defineAction()
Section titled defineAction()
Aggiunto in:
astro@4.15.0
Beta
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.
handler()
property
Section titled handler() property
Aggiunto in:
astro@4.15.0
Beta
defineAction()
accepts a handler()
function containing the server logic to run when the action is called. This function can return data that is automatically serialized and sent to the caller.
Return values are parsed using the devalue library. This supports JSON values, along with instances of Date()
, Map()
, Set()
, or URL()
.
input
validator
Section titled input validator
Aggiunto in:
astro@4.15.0
Beta
The optional input
property accepts a Zod validator 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 used with accept: 'form'
, input
must use the z.object()
validator.
Extension functions including .refine()
, .transform()
, and .pipe()
are also supported on this object. The following validators are supported for form data fields:
- Inputs of type
number
can be validated usingz.number()
- Inputs of type
checkbox
can be validated usingz.boolean()
- Inputs of type
file
can be validated usingz.instanceof(File)
- Multiple inputs of the same
name
can be validated usingz.array(/* validator */)
- All other inputs can be validated using
z.string()
isInputError()
Section titled isInputError()Type: (error?: unknown | ActionError) => boolean
astro@4.15.0
Beta
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.
isInputError()
.
ActionError
Section titled ActionError
Aggiunto in:
astro@4.15.0
Beta
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.
Aggiunto in:
astro@4.15.0
Beta
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 actioninput
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 theContent-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.
message
Section titled message
Aggiunto in:
astro@4.15.0
Beta
The message
property accepts a string. (e.g. “User must be logged in.“)
Built-in Components
Section titled Built-in ComponentsAstro includes several built-in components for you to use in your projects. All built-in components are available in .astro
files via import {} from 'astro:components';
.
You can reference the Props
of these components using the ComponentProp
type utility.
<Code />
Section titled <Code />This component provides syntax highlighting for code blocks at build time (no client-side JavaScript included). The component is powered internally by Shiki and it supports all popular themes and languages. Plus, you can add your custom themes, languages, transformers, and default colors by passing them to the theme
, lang
, transformers
, and defaultColor
attributes respectively.
This component does not inherit the settings from your Shiki configuration. You will have to set them using the component props.
Transformers
Section titled Transformers
Aggiunto in:
astro@4.11.0
Shiki transformers can optionally be applied to code by passing them in through the transformers
property as an array. Since Astro v4.14.0, you can also provide a string for Shiki’s meta
attribute to pass options to transformers.
Note that transformers
only applies classes and you must provide your own CSS rules to target the elements of your code block.
<Fragment />
Section titled <Fragment />A component used with set:*
directives to render HTML content without any additional wrapping elements:
See more about using fragments in Astro syntax.
<Prism />
Section titled <Prism />To use the Prism
highlighter component, first install the @astrojs/prism
package:
This component provides language-specific syntax highlighting for code blocks by applying Prism’s CSS classes. Note that you need to provide a Prism CSS stylesheet (or bring your own) for syntax highlighting to appear! See the Prism configuration section for more details.
See the list of languages supported by Prism where you can find a language’s corresponding alias. And, you can also display your Astro code blocks with lang="astro"
!
<Image />
Section titled <Image />Properties
Section titled Properties- src (required)
- alt (required)
- width and height (required for
public/
and remote images) - format
- quality
- densities
- widths
In addition to the properties above, the <Image />
component accepts all properties accepted by the HTML <img>
tag.
See more in the Images Guide.
<Picture />
Section titled <Picture />
Aggiunto in:
astro@3.3.0
Use the built-in <Picture />
Astro component to display a responsive image with multiple formats and/or sizes.
See more in the Images Guide.
Properties
Section titled Properties<Picture />
accepts all the properties of the <Image />
component, plus the following:
formats
Section titled formatsAn array of image formats to use for the <source>
tags. By default, this is set to ['webp']
.
fallbackFormat
Section titled fallbackFormatFormat to use as a fallback value for the <img>
tag. Defaults to .png
for static images, .gif
for animated images, and .svg
for SVG files.
pictureAttributes
Section titled pictureAttributesAn 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.
<Content />
Section titled <Content />A generic component used to render the content of a content collection entry.
First, query one or more entries using getCollection()
or getEntry()
. Then, the entry.render()
function can return the <Content />
component for use in a .astro
file template.
<ViewTransitions />
Section titled <ViewTransitions />
Aggiunto in:
astro@2.9.0
Opt in to using view transitions on individual pages by importing and adding the <ViewTransitions />
routing component to <head>
on every desired page.
See more about how to control the router and add transition directives to page elements and components.
<Debug />
Section titled <Debug />This component provides a way to inspect values on the client-side, without any JavaScript.
Reference