Content Collections
Questi contenuti non sono ancora disponibili nella tua lingua.
Aggiunto in:
astro@2.0.0
Content collections are the best way to manage and author content in any Astro project. Collections help to organize your documents, validate your frontmatter, and provide automatic TypeScript type-safety for all of your content.
What are Content Collections?
Section titled What are Content Collections?A content collection is any top-level directory inside the reserved src/content
project directory, such as src/content/newsletter
and src/content/authors
. Only content collections are allowed inside the src/content
directory. This directory cannot be used for anything else.
A collection entry is any piece of content stored inside of your content collection directory. Entries can use content authoring formats including Markdown (.md
) and MDX (.mdx
using the MDX integration) or as one of two supported data formats: YAML (.yaml
) and JSON (.json
). We recommend using a consistent naming scheme (lower-case, dashes instead of spaces) for your files to make it easier to find and organize your content, but this is not required. You can also exclude entries from being built by prefixing the filename with an underscore (_).
Directorysrc/content/
Directorynewsletter/ the “newsletter” collection
- week-1.md a collection entry
- week-2.md a collection entry
- week-3.md a collection entry
Once you have a collection, you can start querying your content using Astro’s built-in content APIs.
The “.astro” Directory
Section titled The “.astro” DirectoryAstro stores important metadata for content collections in an .astro
directory in your project. No action is needed on your part to maintain or update this directory. You are encouraged to ignore it entirely while working in your project.
The .astro
directory will be updated for you automatically anytime you run the astro dev
, astro build
commands. You can run astro sync
at any time to update the .astro
directory manually.
If you’re using Git for version control, we recommend ignoring the .astro
directory by adding .astro
to your .gitignore
. This tells Git to ignore this directory and any files inside of it.
Organizing with multiple collections
Section titled Organizing with multiple collectionsIf two files represent different kinds of content (e.g. a blog post and an author profile), they most likely belong in different collections. This is important because many features (frontmatter validation, automatic TypeScript type-safety) require that all entries in a collection share a similar structure.
If you find yourself working with different types of content, you should create multiple collections to represent each type. You can create as many different collections in your project as you’d like.
Directorysrc/content/
Directorynewsletter/
- week-1.md
- week-2.md
Directoryblog/
- post-1.md
- post-2.md
Directoryauthors/
- grace-hopper.json
- alan-turing.json
Organizing with subdirectories
Section titled Organizing with subdirectoriesA content collection is always a top-level folder inside of the src/content/
directory. You cannot nest one collection inside of another. However, you can use subdirectories to organize your content within a collection.
For example, you can use the following directory structure to organize i18n translations within a single docs
collection. When you query this collection, you’ll be able to filter the result by language using the file path.
Directorysrc/content/
Directorydocs/ this collection uses subdirectories to organize by language
Directoryen/
- …
Directoryes/
- …
Directoryde/
- …
Defining Collections
Section titled Defining CollectionsThe src/content/config.ts
file is optional. However, choosing not to define your collections will disable some of their best features like frontmatter schema validation or automatic TypeScript typings.
To get the most out of your content collections, create a src/content/config.ts
file in your project (.js
and .mjs
extensions are also supported.) This is a special file that Astro will automatically load and use to configure your content collections.
Setting up TypeScript
Section titled Setting up TypeScriptIf you do not already extend Astro’s strict
or strictest
recommended TypeScript settings in your tsconfig.json
file, you may need to update your tsconfig.json
to enable strictNullChecks
.
If you use .js
or .mjs
files in an Astro project, you can enable IntelliSense and type checking in your editor by enabling allowJs
in your tsconfig.json
:
Defining a collection schema
Section titled Defining a collection schemaSchemas enforce consistent frontmatter or entry data within a collection. A schema guarantees that this data exists in a predictable form when you need to reference or query it. If any file violates its collection schema, Astro will provide a helpful error to let you know.
Schemas also power Astro’s automatic TypeScript typings for your content. When you define a schema for your collection, Astro will automatically generate and apply a TypeScript interface to it. The result is full TypeScript support when you query your collection, including property autocompletion and type-checking.
To define your first collection, create a src/content/config.ts
file if one does not already exist (.js
and .mjs
extensions are also supported.) This file should:
- Import the proper utilities from
astro:content
. - Define each collection that you’d like to validate. This includes a
type
(introduced in Astro v2.5.0) specifying whether the collection contains content authoring formats like Markdown (type: 'content'
) or data formats like JSON or YAML (type: 'data'
). It also includes aschema
that defines the shape of your frontmatter or entry data. - Export a single
collections
object to register your collections.
Defining multiple collections
Section titled Defining multiple collectionsYou can use defineCollection()
as many times as you want to create multiple schemas. All collections must be exported from inside the single collections
object.
As your project grows, you are also free to reorganize your codebase and move logic out of the src/content/config.ts
file. Defining your schemas separately can be useful for reusing schemas across multiple collections and sharing schemas with other parts of your project.
Using third-party collection schemas
Section titled Using third-party collection schemasYou can import collection schemas from anywhere, including external npm packages. This can be useful when working with themes and libraries that provide their own collection schemas for you to use.
Defining datatypes with Zod
Section titled Defining datatypes with ZodAstro uses Zod to power its content schemas. With Zod, Astro is able to validate every file’s frontmatter within a collection and provide automatic TypeScript types when you go to query content from inside your project.
To use Zod in Astro, import the z
utility from "astro:content"
. This is a re-export of the Zod library, and it supports all of the features of Zod. See Zod’s README for complete documentation on how Zod works and what features are available.
Defining collection references
Section titled Defining collection referencesCollection entries can also “reference” other related entries.
With the reference()
function from the Collections API, you can define a property in a collection schema as an entry from another collection. For example, you can require that every space-shuttle
entry includes a pilot
property which uses the pilot
collection’s own schema for type checking, autocomplete, and validation.
A common example is a blog post that references reusable author profiles stored as JSON, or related post URLs stored in the same collection:
This example blog post specifies the slug
s of related posts and the id
of the post author:
Defining custom slugs
Section titled Defining custom slugsWhen using type: 'content'
, every content entry generates a URL-friendly slug
property from its file id
. The slug is used to query the entry directly from your collection. It is also useful when creating new pages and URLs from your content.
You can override an entry’s generated slug by adding your own slug
property to the file frontmatter. This is similar to the “permalink” feature of other web frameworks. "slug"
is a special, reserved property name that is not allowed in your custom collection schema
and will not appear in your entry’s data
property.
Querying Collections
Section titled Querying CollectionsAstro provides two functions to query a collection and return one (or more) content entries: getCollection()
and getEntry()
.
Both functions return content entries as defined by the CollectionEntry
type.
Accessing referenced data
Section titled Accessing referenced dataAny references defined in your schema must be queried separately after first querying your collection entry. You can use the getEntry()
function again, or getEntries()
, to retrieve the referenced entry from the returned data
object.
Filtering collection queries
Section titled Filtering collection queriesgetCollection()
takes an optional “filter” callback that allows you to filter your query based on an entry’s id
or data
(frontmatter) properties. For collections of type: 'content'
, you can also filter based on slug
.
The slug
property is specific to content collections, and will not be available when filtering collections of JSON or YAML.
You can use this to filter by any content criteria you like. For example, you can filter by properties like draft
to prevent any draft blog posts from publishing to your blog:
You can also create draft pages that are available when running the dev server, but not built in production:
The filter argument also supports filtering by nested directories within a collection. Since the id
includes the full nested path, you can filter by the start of each id
to only return items from a specific nested directory:
Using content in Astro templates
Section titled Using content in Astro templatesOnce you have queried your collection entries, you can access each entry directly inside of your Astro component template. This lets you to render HTML for things like links to your content (using the content slug
) or information about your content (using the data
property).
For information about rendering your content to HTML, see Rendering Content to HTML below.
Passing content as props
Section titled Passing content as propsA component can also pass an entire content entry as a prop.
If you do this, you can use the CollectionEntry
utility to correctly type your components props using TypeScript. This utility takes a string argument that matches the name of your collection schema, and will inherit all of the properties of that collection’s schema.
Rendering content to HTML
Section titled Rendering content to HTMLOnce queried, you can render Markdown and MDX entries to HTML using the entry render()
function property. Calling this function gives you access to rendered content and metadata, including both a <Content />
component and a list of all rendered headings.
Generating Routes from Content
Section titled Generating Routes from ContentContent collections are stored outside of the src/pages/
directory. This means that no routes are generated for your collection items by default. You will need to manually create a new dynamic route to generate HTML pages from your collection entries. Your dynamic route will map the incoming request param (ex: Astro.params.slug
in src/pages/blog/[...slug].astro
) to fetch the correct entry inside a collection.
The exact method for generating routes will depend on your build output
mode: ‘static’ (the default) or ‘server’ (for SSR).
Building for static output (default)
Section titled Building for static output (default)If you are building a static website (Astro’s default behavior), you would use the getStaticPaths()
function to create multiple pages from a single src/pages/
component during your build.
Call getCollection()
inside of getStaticPaths()
to query your content or data collection. Then, create your new URL paths using the slug
property (content collections) or id
property (data collections) of each content entry.
This will generate a new page for every entry in the blog
collection. For example, an entry at src/content/blog/hello-world.md
will have a slug of hello-world
, and therefore its final URL will be /posts/hello-world/
.
If your custom slugs contain the /
character to produce URLs with multiple path segments, you must use a rest parameter ([...slug]
) in the .astro
filename for this dynamic routing page.
Building for server output (SSR)
Section titled Building for server output (SSR)If you are building a dynamic website (using Astro’s SSR support), you are not expected to generate any paths ahead of time during the build. Instead, your page should examine the request (using Astro.request
or Astro.params
) to find the slug
on-demand, and then fetch it using getEntry()
.
Explore the src/pages/
folder of the blog tutorial demo code on GitHub or open it in StackBlitz to see full examples of creating pages from your collections for blog features like a list of blog posts, tags pages, and more!
Migrating from File-Based Routing
Section titled Migrating from File-Based RoutingIf you have an existing Astro project, such as a blog, that uses Markdown or MDX files in subfolders inside src/pages/
, consider migrating related content or data files to content collections.
See how to convert a basic blog example from src/pages/posts/
to src/content/posts
in our step-by-step tutorial that uses the codebase from the Build a Blog tutorial’s finished project.
Enabling Build Caching
Section titled Enabling Build Caching
Aggiunto in:
astro@3.5.0
Experimental
If you are working with large collections, you may wish to enable cached builds with the experimental.contentCollectionCache
flag. This experimental feature optimizes Astro’s build process, enabling unchanged collections to be stored and reused between builds.
In many cases, this can lead to significant build performance improvements.
While this feature stabilizes, you may run into issues with the stored cache. You can always reset your build cache by running the following command:
Modifying Frontmatter with Remark
Section titled Modifying Frontmatter with RemarkNot recommended. Remark and rehype plugins access the raw Markdown or MDX document frontmatter. This means that remarkPluginFrontmatter
frontmatter is handled separately from your type-safe schema
, and will not reflect any changes or defaults applied through Astro. Use at your own risk!
Astro supports remark or rehype plugins that modify your frontmatter directly. You can access this modified frontmatter inside of a content entry by using the remarkPluginFrontmatter
property returned from render()
:
The remark and rehype pipelines only run when your content is rendered, which explains why remarkPluginFrontmatter
is only available after you call render()
on your content entry. In contrast, getCollection()
and getEntry()
cannot return these values directly because they do not render your content.
Working with dates in the frontmatter
Section titled Working with dates in the frontmatterSeveral date formats are possible in content collections, but your collection’s schema must match the format used in your Markdown or MDX YAML frontmatter.
YAML uses the ISO-8601 standard to express dates. Use the format yyyy-mm-dd
(e.g. 2021-07-28
) along with a schema type of z.date()
:
The date format will be specified in UTC if a timezone is not provided. If you need to specify a timezone, you can use the ISO 8601 format.
To render only the YYYY-MM-DD
from the full UTC timestamp, use the JavaScript slice
method to remove the timestamp:
To see an example of using toLocaleDateString
to format the day, month, and year instead, see the <FormattedDate />
component in the official Astro blog template.