diff --git a/public/_redirects b/public/_redirects index a1a72f2a44138..f1ad8a8ad744c 100644 --- a/public/_redirects +++ b/public/_redirects @@ -1,32 +1,33 @@ # Moved content # When moving a page, usually you’ll want to add a redirect to the bottom of this block. -/:lang/install/auto /:lang/install-and-setup/ -/:lang/install/manual /:lang/install-and-setup/ -/:lang/core-concepts/project-structure /:lang/basics/project-structure/ -/:lang/core-concepts/astro-components /:lang/basics/astro-components/ -/:lang/core-concepts/astro-pages /:lang/basics/astro-pages/ -/:lang/core-concepts/layouts /:lang/basics/layouts/ -/:lang/core-concepts/astro-syntax /:lang/basics/astro-syntax/ -/:lang/core-concepts/rendering-modes /:lang/basics/rendering-modes/ -/:lang/core-concepts/routing /:lang/guides/routing/ -/:lang/core-concepts/endpoints /:lang/guides/endpoints/ -/:lang/core-concepts/framework-components /:lang/guides/framework-components/ -/:lang/core-concepts/sharing-state /:lang/recipes/sharing-state-islands/ -/:lang/reference/dev-overlay-plugin-reference /:lang/reference/dev-toolbar-app-reference/ -/:lang/core-concepts/partial-hydration /:lang/concepts/islands/ -/:lang/guides/publish-to-npm /:lang/reference/publish-to-npm/ -/:lang/concepts/mpa-vs-spa /:lang/concepts/why-astro/ -/:lang/deploy/:service /:lang/guides/deploy/:service -/:lang/guides/deploy/layer-zero /:lang/guides/deploy/edgio/ -/:lang/guides/client-side-routing /:lang/guides/view-transitions/ -/:lang/guides/assets /:lang/guides/images/ -/en/guides/aliases /en/guides/imports/#aliases -/:lang/guides/aliases /:lang/guides/imports/ -/:lang/guides/integrations-guide/image /:lang/guides/images/ -/:lang/migration/0.21.0 /:lang/guides/upgrade-to/v1/ -/:lang/migrate /:lang/guides/upgrade-to/v1/ -/:lang/recipes/studio /:lang/guides/astro-db/ -/:lang/recipes /:lang/community-resources/content/ +/:lang/install/auto /:lang/install-and-setup/ +/:lang/install/manual /:lang/install-and-setup/ +/:lang/core-concepts/project-structure /:lang/basics/project-structure/ +/:lang/core-concepts/astro-components /:lang/basics/astro-components/ +/:lang/core-concepts/astro-pages /:lang/basics/astro-pages/ +/:lang/core-concepts/layouts /:lang/basics/layouts/ +/:lang/core-concepts/astro-syntax /:lang/basics/astro-syntax/ +/:lang/core-concepts/rendering-modes /:lang/basics/rendering-modes/ +/:lang/core-concepts/routing /:lang/guides/routing/ +/:lang/core-concepts/endpoints /:lang/guides/endpoints/ +/:lang/core-concepts/framework-components /:lang/guides/framework-components/ +/:lang/core-concepts/sharing-state /:lang/recipes/sharing-state-islands/ +/:lang/reference/dev-overlay-plugin-reference /:lang/reference/dev-toolbar-app-reference/ +/:lang/core-concepts/partial-hydration /:lang/concepts/islands/ +/:lang/guides/publish-to-npm /:lang/reference/publish-to-npm/ +/:lang/concepts/mpa-vs-spa /:lang/concepts/why-astro/ +/:lang/deploy/:service /:lang/guides/deploy/:service +/:lang/guides/deploy/layer-zero /:lang/guides/deploy/edgio/ +/:lang/guides/client-side-routing /:lang/guides/view-transitions/ +/:lang/guides/assets /:lang/guides/images/ +/en/guides/aliases /en/guides/imports/#aliases +/:lang/guides/aliases /:lang/guides/imports/ +/:lang/guides/integrations-guide/image /:lang/guides/images/ +/:lang/migration/0.21.0 /:lang/guides/upgrade-to/v1/ +/:lang/migrate /:lang/guides/upgrade-to/v1/ +/:lang/recipes/studio /:lang/guides/astro-db/ +/:lang/recipes /:lang/community-resources/content/ +/:lang:/reference/api-reference/#astrocanonicalurl /:lang:/reference/api-reference/#astrourl # Very old docs site redirects # Once upon a time these URLs existed, so we try to keep them meaning something. diff --git a/src/content/docs/en/reference/api-reference.mdx b/src/content/docs/en/reference/api-reference.mdx index be30938da1f20..47a98b9e93838 100644 --- a/src/content/docs/en/reference/api-reference.mdx +++ b/src/content/docs/en/reference/api-reference.mdx @@ -46,20 +46,25 @@ Read more in the [Vite documentation](https://vitejs.dev/guide/features.html#glo ::: #### Markdown Files -Markdown files have the following interface: +Markdown files loaded with `Astro.glob()` return the following `MarkdownInstance` interface: ```ts export interface MarkdownInstance> { /* Any data specified in this file's YAML frontmatter */ frontmatter: T; - /* The file path of this file */ + /* 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: AstroComponent; + Content: AstroComponentFactory; + /** (Markdown only) Raw Markdown file content, excluding layout HTML and YAML 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; } ``` @@ -89,7 +94,7 @@ export interface AstroInstance { file: string; /* The URL for this file (if it is in the pages directory) */ url: string | undefined; - default: AstroComponent; + default: AstroComponentFactory; } ``` @@ -160,6 +165,11 @@ See also: [`params`](#params) ### `Astro.request` +

+ +**Type:** `Request` +

+ `Astro.request` is a standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object. It can be used to get the `url`, `headers`, `method`, and even body of the request. ```astro @@ -175,6 +185,10 @@ With the default `output: 'static'` option, `Astro.request.url` does not contain ### `Astro.response` +

+ +**Type:** `ResponseInit & { readonly headers: Headers }` +

`Astro.response` is a standard `ResponseInit` object. It has the following structure. @@ -204,14 +218,19 @@ Astro.response.headers.set('Set-Cookie', 'a=b; Path=/;'); ### `Astro.cookies` -

+

+ +**Type:** `AstroCookies`
+ +

`Astro.cookies` contains utilities for reading and manipulating cookies in [server-side rendering](/en/guides/server-side-rendering/) mode. ##### `get`

-**Type:** `(key: string, options?: CookieGetOptions) => AstroCookie` + +**Type:** (key: string, options?: AstroCookieGetOptions) => AstroCookie | undefined

Gets the cookie as an [`AstroCookie`](#astrocookie) object, which contains the `value` and utility functions for converting the cookie to non-string types. @@ -219,7 +238,8 @@ Gets the cookie as an [`AstroCookie`](#astrocookie) object, which contains the ` ##### `has`

-**Type:** `(key: string) => boolean` + +**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`. @@ -227,7 +247,8 @@ Whether this cookie exists. If the cookie has been set via `Astro.cookies.set()` ##### `set`

-**Type:** `(key: string, value: string | number | boolean | object, options?: CookieSetOptions) => void` + +**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](https://www.npmjs.com/package/cookie#options-1), such as the `maxAge` or `httpOnly`. @@ -235,16 +256,27 @@ Sets the cookie `key` to the given value. This will attempt to convert the cooki ##### `delete`

-**Type:** `(key: string, options?: CookieDeleteOptions) => void` + +**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`](#astrocookie) with a `value` of `undefined`. Options available when deleting a cookie are: `domain`, `path`, `httpOnly`, `sameSite`, and `secure`. +##### `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. + ##### `headers`

+ **Type:** `() => Iterator`

@@ -257,7 +289,8 @@ Getting a cookie via `Astro.cookies.get()` returns a `AstroCookie` type. It has ##### `value`

-**Type:** `string | undefined` + +**Type:** `string`

The raw string value of the cookie. @@ -265,6 +298,7 @@ The raw string value of the cookie. ##### `json`

+ **Type:** `() => Record`

@@ -273,6 +307,7 @@ Parses the cookie value via `JSON.parse()`, returning an object. Throws if the c ##### `number`

+ **Type:** `() => number`

@@ -281,16 +316,17 @@ Parses the cookie value as a Number. Returns NaN if not a valid number. ##### `boolean`

+ **Type:** `() => boolean`

Converts the cookie value to a boolean. -#### `CookieGetOptions` +#### `AstroCookieGetOptions`

-Getting a cookie also allows specifying options via the `CookieGetOptions` interface: +Getting a cookie also allows specifying options via the `AstroCookieGetOptions` interface: ##### `decode` @@ -300,31 +336,34 @@ Getting a cookie also allows specifying options via the `CookieGetOptions` inter Allows customization of how a cookie is deserialized into a value. -#### `CookieSetOptions` +#### `AstroCookieSetOptions`

-Setting a cookie via `Astro.cookies.set()` allows passing in a `CookieSetOptions` to customize how the cookie is serialized. +Setting a cookie via `Astro.cookies.set()` allows passing in a `AstroCookieSetOptions` to customize how the cookie is serialized. ##### `domain`

+ **Type:** `string`

Specifies the domain. If no domain is set, most clients will interpret to apply to the current domain. - ##### `expires` +##### `expires` -

- **Type:** `Date` -

+

+ +**Type:** `Date` +

Specifies the date on which the cookie will expire. ##### `httpOnly`

+ **Type:** `boolean`

@@ -333,6 +372,7 @@ If true, the cookie will not be accessible client-side. ##### `maxAge`

+ **Type:** `number`

@@ -341,6 +381,7 @@ Specifies a number, in seconds, for which the cookie is valid. ##### `path`

+ **Type:** `string`

@@ -349,6 +390,7 @@ Specifies a subpath of the domain in which the cookie is applied. ##### `sameSite`

+ **Type:** `boolean | 'lax' | 'none' | 'strict'`

@@ -357,6 +399,7 @@ Specifies the value of the [SameSite](https://datatracker.ietf.org/doc/html/draf ##### `secure`

+ **Type:** `boolean`

@@ -365,6 +408,7 @@ If true, the cookie is only set on https sites. ##### `encode`

+ **Type:** `(value: string) => string`

@@ -372,7 +416,10 @@ Allows customizing how the cookie is serialized. ### `Astro.redirect()` +

+ **Type:** `(path: string, status?: number) => Response` +

Allows you to redirect to another page, and optionally provide an [HTTP response status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages) as a second parameter. @@ -397,19 +444,13 @@ if (!isLoggedIn(cookie)) { --- ``` -### `Astro.canonicalURL` - -:::caution[Deprecated] -Use [`Astro.url`](#astrourl) to construct your own canonical URL. -::: - -The [canonical URL][canonical] of the current page. - ### `Astro.rewrite()` -

+

-**Type:** `(rewritePayload: string | URL | Request) => Promise` +**Type:** `(rewritePayload: string | URL | Request) => Promise`
+ +

Allows you to serve content from a different URL or path without redirecting the browser to a new page. @@ -445,7 +486,11 @@ return Astro.rewrite(new Request(new URL("../", Astro.url), { ### `Astro.url` -

+

+ +**Type:** `URL`
+ +

A [URL](https://developer.mozilla.org/en-US/docs/Web/API/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. @@ -472,7 +517,11 @@ const socialImageURL = new URL('/images/preview.png', Astro.url); ### `Astro.clientAddress` -

+

+ +**Type:** `string`
+ +

Specifies the [IP address](https://en.wikipedia.org/wiki/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. @@ -486,11 +535,20 @@ const ip = Astro.clientAddress; ### `Astro.site` +

+ +**Type:** `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` -

+

+ +**Type:** `string`
+ +

`Astro.generator` is a convenient way to add a [``](https://html.spec.whatwg.org/multipage/semantics.html#meta-generator) tag with your current version of Astro. It follows the format `"Astro v1.x.x"`. @@ -513,7 +571,10 @@ const ip = Astro.clientAddress; #### `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. @@ -532,7 +593,10 @@ You can check whether content for a specific slot name exists with `Astro.slots. #### `Astro.slots.render()` +

+ **Type:** `(slotName: string, args?: any[]) => Promise` +

You can asynchronously render the contents of a slot to a string of HTML using `Astro.slots.render()`. @@ -638,6 +702,11 @@ And would render HTML like this: ### `Astro.locals` +

+ + +

+ `Astro.locals` is an object containing any values from the [`context.locals`](#contextlocals) object from a middleware. Use this to access data returned by middleware in your `.astro` files. ```astro title="src/pages/Orders.astro" @@ -655,6 +724,12 @@ const orders = Array.from(Astro.locals.orders.entries()); ### `Astro.preferredLocale` +

+ +**Type:** `string | undefined`
+ +

+ `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. @@ -663,6 +738,12 @@ This property is only available when building for SSR (server-side rendering) an ### `Astro.preferredLocaleList` +

+ +**Type:** `string[] | undefined`
+ +

+ `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. @@ -673,6 +754,12 @@ This property is only available when building for SSR (server-side rendering) an ### `Astro.currentLocale` +

+ +**Type:** `string | undefined`
+ +

+ 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`. ## Endpoint Context @@ -717,6 +804,11 @@ See also: [`params`](#params) ### `context.props` +

+ + +

+ `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. ```ts title="src/pages/posts/[id].json.ts" @@ -741,6 +833,11 @@ See also: [Data Passing with `props`](#data-passing-with-props) ### `context.request` +

+ +**Type:** `Request` +

+ A standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object. It can be used to get the `url`, `headers`, `method`, and even body of the request. ```ts @@ -755,18 +852,35 @@ See also: [Astro.request](#astrorequest) ### `context.cookies` +

+ +**Type:** `AstroCookies` +

+ `context.cookies` contains utilities for reading and manipulating cookies. See also: [Astro.cookies](#astrocookies) ### `context.url` +

+ +**Type:** `URL`
+ +

+ A [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) object constructed from the current `context.request.url` URL string value. See also: [Astro.url](#astrourl) ### `context.clientAddress` +

+ +**Type:** `string`
+ +

+ Specifies the [IP address](https://en.wikipedia.org/wiki/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. ```ts @@ -782,12 +896,24 @@ See also: [Astro.clientAddress](#astroclientaddress) ### `context.site` +

+ +**Type:** `URL | undefined`
+ +

+ `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](#astrosite) ### `context.generator` +

+ +**Type:** `string`
+ +

+ `context.generator` is a convenient way to indicate the version of Astro your project is running. It follows the format `"Astro v1.x.x"`. ```ts title="src/pages/site-info.json.ts" @@ -803,6 +929,12 @@ See also: [Astro.generator](#astrogenerator) ### `context.redirect()` +

+ +**Type:** `(path: string, status?: number) => Response`
+ +

+ `context.redirect()` returns a [Response](https://developer.mozilla.org/en-US/docs/Web/API/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. ```ts @@ -817,9 +949,11 @@ See also: [`Astro.redirect()`](#astroredirect) ### `context.rewrite()` -

+

-**Type:** `(rewritePayload: string | URL | Request) => Promise` +**Type:** `(rewritePayload: string | URL | Request) => Promise`
+ +

Allows you to serve content from a different URL or path without redirecting the browser to a new page. @@ -863,6 +997,8 @@ See also: [`Astro.rewrite()`](#astrorewrite) ### `context.locals` +

+ `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`: @@ -892,6 +1028,8 @@ See also: [`Astro.locals`](#astrolocals) ## `getStaticPaths()` +**Type:** `(options: GetStaticPathsOptions) => Promise | 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. @@ -1021,7 +1159,7 @@ const { page } = Astro.props; - `/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 +- `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 @@ -1032,6 +1170,7 @@ Pagination will pass a `page` prop to every rendered page that represents a sing ##### `page.data`

+ **Type:** `Array`

@@ -1040,6 +1179,7 @@ Array of data returned from `data()` for the current page. ##### `page.start`

+ **Type:** `number`

@@ -1048,6 +1188,7 @@ Index of first item on current page, starting at `0`. (e.g. if `pageSize: 25`, t ##### `page.end`

+ **Type:** `number`

@@ -1056,7 +1197,9 @@ Index of last item on current page. ##### `page.size`

-**Type:** `number` + +**Type:** `number`
+**Default:** `10`

How many items per-page. @@ -1064,6 +1207,7 @@ How many items per-page. ##### `page.total`

+ **Type:** `number`

@@ -1072,6 +1216,7 @@ The total number of items across all pages. ##### `page.currentPage`

+ **Type:** `number`

@@ -1080,6 +1225,7 @@ The current page number, starting with `1`. ##### `page.lastPage`

+ **Type:** `number`

@@ -1088,6 +1234,7 @@ The total number of pages. ##### `page.url.current`

+ **Type:** `string`

@@ -1096,6 +1243,7 @@ Get the URL of the current page (useful for canonical URLs). ##### `page.url.prev`

+ **Type:** `string | undefined`

@@ -1104,6 +1252,7 @@ Get the URL of the previous page (will be `undefined` if on page 1). If a value ##### `page.url.next`

+ **Type:** `string | undefined`

@@ -1112,7 +1261,9 @@ Get the URL of the next page (will be `undefined` if no more pages). If a value ##### `page.url.first`

-**Type:** `string | undefined` + +**Type:** `string | undefined`
+

Get the URL of the first page (will be `undefined` if on page 1). If a value is set for [`base`](/en/reference/configuration-reference/#base), prepend the base path to the URL. @@ -1120,7 +1271,9 @@ Get the URL of the first page (will be `undefined` if on page 1). If a value is ##### `page.url.last`

-**Type:** `string | undefined` + +**Type:** `string | undefined`
+

Get the URL of the last page (will be `undefined` if no more pages). If a value is set for [`base`](/en/reference/configuration-reference/#base), prepend the base path to the URL. @@ -1141,6 +1294,11 @@ export default function () { ### `getImage()` +

+ +**Type:** `(options: UnresolvedImageTransform) => Promise` +

+ :::caution `getImage()` relies on server-only APIs and breaks the build when used on the client. ::: @@ -1160,13 +1318,24 @@ const optimizedBackground = await getImage({src: myBackground, format: 'avif'})
``` -It returns an object with the following properties: +It returns an object with the following type: -```js -{ - options: {...} // Original parameters passed - src: "https//..." // Path to the generated image - attributes: {...} // Additional HTML attributes needed to render the image (width, height, style, etc..) +```ts +type GetImageResult = { + /* Additional HTML attributes needed to render the image (width, height, style, etc..) */ + attributes: Record; + /* 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; + }; } ``` @@ -1178,6 +1347,11 @@ Content collections offer APIs to configure and query your Markdown or MDX docum ### `defineCollection()` +

+ +**Type:** `(input: CollectionConfig) => CollectionConfig` +

+ `defineCollection()` is a utility to configure a collection in a `src/content/config.*` file. ```ts @@ -1200,10 +1374,12 @@ This function accepts the following properties: #### `type` -

+

-**Type:** `'content' | 'data'` -**Default:** `'content'` +**Type:** `'content' | 'data'`
+**Default:** `'content'`
+ +

`type` is a string that defines the type of entries stored within a collection: @@ -1216,7 +1392,10 @@ This means collections **cannot** store a mix of content and data formats. You m #### `schema` -**Type:** `TSchema extends ZodType` +

+ +**Type:** 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](https://github.com/colinhacks/zod). @@ -1224,7 +1403,11 @@ This means collections **cannot** store a mix of content and data formats. You m ### `reference()` -**Type:** `(collection: string) => ZodEffects` +

+ +**Type:** `(collection: string) => ZodEffects`
+ +

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. @@ -1255,7 +1438,10 @@ export const collections = { blog, authors }; ### `getCollection()` +

+ **Type:** `(collection: string, filter?: (entry: CollectionEntry) => boolean) => CollectionEntry[]` +

`getCollection()` is a function that retrieves a list of content collection entries by collection name. @@ -1282,7 +1468,6 @@ const draftBlogPosts = await getCollection('blog', ({ data }) => {

**Types:** - - `(collection: string, contentSlugOrDataId: string) => CollectionEntry` - `({ collection: string, id: string }) => CollectionEntry` - `({ collection: string, slug: string }) => CollectionEntry` @@ -1311,7 +1496,6 @@ See the `Content Collections` guide for examples of [querying collection entries

**Types:** - - `(Array<{ collection: string, id: string }>) => Array>` - `(Array<{ collection: string, slug: string }>) => Array>` @@ -1330,7 +1514,10 @@ const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts ### `getEntryBySlug()` -**Type:** `(collection: string, slug: string) => CollectionEntry` +

+ +**Type:** `(collection: string, slug: string) => Promise>` +

:::caution[Deprecated] Use the [`getEntry()` function](#getentry) to query content entries. This accepts the same arguments as `getEntryBySlug()`, and supports querying by `id` for JSON or YAML collections. @@ -1349,6 +1536,29 @@ const enterprise = await getEntryBySlug('blog', 'enterprise'); [See the `Content Collection` guide](/en/guides/content-collections/#querying-collections) for example usage. +### `getDataEntryById()` + +

+ +**Type:** `(collection: string, id: string) => Promise>`
+ +

+ +:::caution[Deprecated] +Use the [`getEntry()` function](#getentry) 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`. + + +```astro +--- +import { getDataEntryById } from 'astro:content'; + +const picardProfile = await getDataEntryById('captains', 'picard'); +--- +``` + ### Collection Entry Type Query functions including [`getCollection()`](#getcollection), [`getEntry()`](#getentry), and [`getEntries()`](#getentries) each return entries with the `CollectionEntry` type. This type is available as a utility from `astro:content`: @@ -1424,6 +1634,8 @@ The `astro:content` module also exports the following types for use in your Astr #### `CollectionKey` +

+ 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. ```ts @@ -1436,10 +1648,14 @@ async function getCollection(collection: CollectionKey) { #### `ContentCollectionKey` +

+ A string union of all the names of `type: 'content'` collections defined in your `src/content/config.*` file. #### `DataCollectionKey` +

+ A string union of all the names of `type: 'data'` collection defined in your `src/content/config.*` file. #### `SchemaContext` @@ -1477,7 +1693,9 @@ Middleware allows you to intercept requests and responses and inject behaviors d ### `onRequest()` -A required exported function from `src/middleware.js` that will be called before rendering every page or API route. It accepts two optional arguments: [context](#contextlocals) and [next()](#next). `onRequest()` must return a `Response`: either directly, or by calling `next()`. +**Type:** `(context: APIContext, next: MiddlewareNext) => Promise | Response | Promise | 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](#context) and [next()](#next). `onRequest()` must return a `Response`: either directly, or by calling `next()`. ```js title="src/middleware.js" export function onRequest (context, next) { @@ -1488,20 +1706,35 @@ export function onRequest (context, next) { }; ``` -### `next()` +#### `context` + +

-A function that intercepts (reads and modifies) the `Response` of a `Request` or calls the "next" middleware in the chain and returns a `Response`. For example, this function could modify the HTML body of a response. +**Type:** `APIContext` +

-This is an optional argument of `onRequest()`, and may provide the required `Response` returned by the middleware. +The first argument of `onRequest()` is a context object. It mirrors many of the `Astro` global properties. -

+See [Endpoint contexts](#endpoint-context) for more information about the context object. -**Type:** `(rewritePayload?: string | URL | Request) => Promise` +#### `next()` -It accepts an optional URL path parameter in the form of a string, `URL`, or `Request` to [rewrite](/en/guides/routing/#rewrites) the current request without retriggering a new rendering phase. +

+ +**Type:** `(rewritePayload?: string | URL | Request) => Promise`
+

+ +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](/en/guides/routing/#rewrites) the current request without retriggering a new rendering phase. ### `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. ```js title="src/middleware.js" @@ -1516,12 +1749,24 @@ export const onRequest = sequence(validation, auth, greeting); ### `createContext()` +

+ +**Type:** `(context: CreateContext) => APIContext`
+ +

+ A low-level API to create an [`APIContext`](#endpoint-context)to be passed to an Astro middleware `onRequest()` function. This function can be used by integrations/adapters to programmatically execute the Astro middleware. ### `trySerializeLocals()` +

+ +**Type:** `(value: unknown) => string`
+ +

+ 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`) @@ -1543,7 +1788,10 @@ For features and usage examples, [see our i18n routing guide](/en/guides/interna ### `getRelativeLocaleUrl()` -`getRelativeLocaleUrl(locale: string, path?: string, options?: GetLocaleOptions): string` +

+ +**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. @@ -1573,7 +1821,10 @@ getRelativeLocaleUrl("fr_CA", "getting-started", { ### `getAbsoluteLocaleUrl()` -`getAbsoluteLocaleUrl(locale: string, path: string, options?: GetLocaleOptions): string` +

+ +**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. @@ -1606,21 +1857,29 @@ getAbsoluteLocaleUrl("fr_CA", "getting-started", { ### `getRelativeLocaleUrlList()` -`getRelativeLocaleUrlList(path?: string, options?: GetLocaleOptions): string[]` +

+**Type:** `(path?: string, options?: GetLocaleOptions) => string[]` +

Use this like [`getRelativeLocaleUrl`](#getrelativelocaleurl) to return a list of relative paths for all the locales. ### `getAbsoluteLocaleUrlList()` -`getAbsoluteLocaleUrlList(path?: string, options?: GetLocaleOptions): string[]` +

+ +**Type:** `(path?: string, options?: GetLocaleOptions) => string[]` +

Use this like [`getAbsoluteLocaleUrl`](/en/guides/internationalization/#custom-locale-paths) to return a list of absolute paths for all the locales. ### `getPathByLocale()` -`getPathByLocale(locale: string): string` +

+ +**Type:** `(locale: string) => string` +

A function that returns the `path` associated to one or more `codes` when [custom locale paths](/en/guides/internationalization/#custom-locale-paths) are configured. @@ -1644,7 +1903,10 @@ getPathByLocale("fr-CA"); // returns "french" ### `getLocaleByPath` - `getLocaleByPath(path: string): string` +

+ +**Type:** `(path: string) => string` +

A function that returns the `code` associated to a locale `path`. @@ -1667,9 +1929,11 @@ getLocaleByPath("french"); // returns "fr" because that's the first code configu ### `redirectToDefaultLocale()` -`redirectToDefaultLocale(context: APIContext, statusCode?: ValidRedirectStatus): Promise` +

-

+**Type:** `(context: APIContext, statusCode?: ValidRedirectStatus) => Promise`
+ +

:::note Available only when `i18n.routing` is set to `"manual"` @@ -1692,9 +1956,11 @@ export const onRequest = defineMiddleware((context, next) => { ### `redirectToFallback()` -`redirectToFallback(context: APIContext, response: Response): Promise` +

-

+**Type:** `(context: APIContext, response: Response) => Promise`
+ +

:::note Available only when `i18n.routing` is set to `"manual"` @@ -1717,9 +1983,11 @@ export const onRequest = defineMiddleware(async (context, next) => { ### `notFound()` -`notFound(context: APIContext, response: Response): Promise` +

-

+**Type:** `(context: APIContext, response?: Response) => Promise | undefined`
+ +

:::note Available only when `i18n.routing` is set to `"manual"` @@ -1746,9 +2014,11 @@ export const onRequest = defineMiddleware((context, next) => { ### `middleware()` -`middleware(options: { prefixDefaultLocale: boolean, redirectToDefaultLocale: boolean })` +

-

+**Type:** `(options: { prefixDefaultLocale: boolean, redirectToDefaultLocale: boolean }) => MiddlewareHandler`
+ +

:::note Available only when `i18n.routing` is set to `"manual"` @@ -1779,9 +2049,11 @@ export const onRequest = sequence(customLogic, middleware({ ### `requestHasLocale()` -`requestHasLocale(context: APIContext): boolean` +

-

+**Type:** `(context: APIContext) => boolean`
+ +

:::note Available only when `i18n.routing` is set to `"manual"` @@ -2015,6 +2287,8 @@ const { Content } = await entry.render(); ### `` +

+ Opt in to using view transitions on individual pages by importing and adding the `` routing component to `` on every desired page. ```astro title="src/pages/index.astro" ins={2,7}