Pular para o conteúdo

Content Collections API Reference

Este conteúdo não está disponível em sua língua ainda.

Adicionado em: astro@2.0.0

Build-time content collections offer APIs to configure, query, and render your local Markdown, MDX, Markdoc, YAML, TOML, or JSON files, as well as remote content.

Adicionado em: astro@6.0.0 Beta

Live content collections offer APIs to configure, query, and render fresh, up-to-the-moment live data from remote sources.

For features and usage examples, see our content collections guide.

import {
z,
defineCollection,
defineLiveCollection,
getCollection,
getLiveCollection,
getEntry,
getLiveEntry,
getEntries,
reference,
render
} from 'astro:content';

Type: (input: CollectionConfig) => CollectionConfig

Adicionado em: astro@2.0.0

A utility to configure a collection in a src/content.config.* file.

src/content.config.ts
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` export
export const collections = { blog };

This function accepts the following properties:

Type: () => Promise<Array<{ id: string, [key: string]: any }> | Record<string, Record<string, any>>> | Loader

Adicionado em: astro@5.0.0

Either an object or a function that allows you to load data from any source, local or remote, into a build-time content collection. (For live collections, see the live loader property.)

Learn about build-time collection loaders with guided explanations and example usage.

Type: ZodType | (context: SchemaContext) => ZodType

Adicionado em: astro@2.0.0

An optional Zod object or function that returns a Zod object to configure the type and shape of document frontmatter for a collection. Each value must use a Zod validator. (For live collections, see the live schema property.)

Learn about defining a collection schema using Zod with guided explanations, example usage, and common datatypes.

Type: (config: LiveCollectionConfig) => LiveCollectionConfig

Adicionado em: astro@6.0.0 Beta

A utility to configure a live collection in a src/live.config.* file.

src/live.config.ts
import { defineLiveCollection } from 'astro:content';
import { storeLoader } from '@example/astro-loader';
const products = defineLiveCollection({
loader: storeLoader({
apiKey: process.env.STORE_API_KEY,
endpoint: 'https://api.example.com/v1',
}),
});
// Expose your defined collection to Astro
// with the `collections` export
export const collections = { products };

This function accepts the following properties:

Type: LiveLoader

Adicionado em: astro@6.0.0 Beta

An object that allows you to load data at runtime from a remote source into a live content collection. (For build-time collections, see the build-time loader property.)

Learn how to create a live loader with guided explanations and example usage.

Type: ZodType

Adicionado em: astro@6.0.0 Beta

An optional Zod object to configure the type and shape of your data for a live collection. Each value must use a Zod validator. (For build-time collections, see the build-time schema property.)

When you define a schema, it will take precedence over the live loader’s types when you query the collection.

Learn about using Zod schemas with live collections through guided explanations and usage examples.

Type: (collection: CollectionKey) => ZodEffects<ZodString, { collection: CollectionKey, id: string }>

Adicionado em: astro@2.5.0

A function used in the content config to define a relationship, or “reference”, from one collection to another. This accepts a collection name and transforms 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:

src/content.config.ts
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 };

Validation of referenced entries happens at runtime when using getEntry() or getEntries():

src/pages/[posts].astro
// if a referenced entry is invalid, this will return undefined.
const relatedPosts = await getEntries(blogPost.data.relatedPosts);
Learn how to define and use collection references with guided explanations and usage examples.

Type: (collection: CollectionKey, filter?: (entry: CollectionEntry) => boolean) => CollectionEntry[]

Adicionado em: astro@2.0.0

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.

src/pages/blog/index.astro
---
import { getCollection } from 'astro:content';
// Get all `src/data/blog/` entries
const allBlogPosts = await getCollection('blog');
// Only return posts with `draft: true` in the frontmatter
const draftBlogPosts = await getCollection('blog', ({ data }) => {
return data.draft === true;
});
---
Learn how to query build time collections with guided explanations and example usage.

Type: (collection: string, filter?: LiveLoaderCollectionFilterType) => Promise<LiveDataCollectionResult>

Adicionado em: astro@6.0.0 Beta

A function that retrieves a list of live content collection entries by collection name.

It returns all items in the collection by default, and accepts an optional filter object whose shape is defined by the collection’s loader. This allows you to query for only some items in a collection or retrieve data in a different form, depending on your API’s capabilities.

src/pages/shop/index.astro
---
import { getLiveCollection } from 'astro:content';
// Get all `products` entries from your API
const allProducts = await getLiveCollection('products');
// Only return `products` that should be featured
const featuredProducts = await getLiveCollection('products', { featured: true });
---
Learn how to access live collections data with guided explanations and example usage.

Types:

Adicionado em: astro@2.5.0

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:

src/pages/index.astro
---
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);
---
Learn more about querying build time collections with guided explanations and example usage.

Type: (collection: string, filter: string | LiveLoaderEntryFilterType) => Promise<LiveDataEntryResult>

Adicionado em: astro@6.0.0 Beta

A function that retrieves a single live collection entry by collection name and an optional filter, either as an id string or as a type-safe object.

src/pages/blog/[id].astro
---
import { getLiveEntry } from 'astro:content';
const liveCollectionsPost = await getLiveEntry('blog', Astro.params.id);
const mattDraft = await getLiveEntry('blog', {
status: 'draft',
author: 'matt',
});
---
Learn how to access live collections data with guided explanations and example usage.

Type: ({ collection: CollectionKey, id: string }[]) => CollectionEntry[]

Adicionado em: astro@2.5.0

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.

src/pages/blog/enterprise/index.astro
---
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<RenderResult>

Adicionado em: astro@5.0.0

A function to compile a given entry for rendering. This returns the following properties:

src/pages/blog/entry-1.astro
---
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);
---
Learn how to render the body content of entries with guided explanations and example usage.
import type {
CollectionEntry,
CollectionKey,
SchemaContext,
} from 'astro:content';

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';

A generic type to use with the name of the collection you’re querying to represent a single entry in that collection. For example, an entry in your blog collection would have the type CollectionEntry<'blog'>.

Each CollectionEntry is an object with the following values:

Type: string

A unique ID. Note that all IDs from Astro’s built-in glob() loader are slugified.

Type: CollectionKey

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.

Type: RenderedContent | undefined

The rendered content of an entry as stored by your loader. For example, this can be the rendered content of a Markdown entry, or HTML from a CMS.

Type: string | undefined

The path to an entry relative to your project directory. This value is only available for local entries.

Example Type: 'blog' | 'authors' | ...

Adicionado em: 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().

src/utils/collections.ts
import { type CollectionKey, getCollection } from 'astro:content';
export 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:

src/content.config.ts
import { defineCollection, z, type SchemaContext } from "astro:content";
import { glob } from 'astro/loaders';
export const imageSchema = ({ image }: SchemaContext) =>
z.object({
image: image(),
description: z.string().optional(),
});
const blog = defineCollection({
loader: glob({ pattern: '**/*.md', base: './src/data/blog' }),
schema: ({ image }) => z.object({
title: z.string(),
permalink: z.string().optional(),
image: imageSchema({ image })
}),
});
Contribua Comunidade Sponsor