Content Collections

Documentation written in Markdown has a way of drifting. A page called “install” ends up with a different frontmatter shape from a page called “configure”, one release adds a field nobody validates, and the template that renders the collection discovers the inconsistency at runtime. Content collections exist to move that discovery to build time. A collection declares the shape of its entries once, in a schema, and every file that does not match the schema fails the build with a message naming the file and the field. What you get in return is a typed API: the renderer knows that entry.data.title is a string and that entry.data.pubDate is a date, and the editor can autocomplete both.

A collection is defined in the content configuration file. In current versions that file is src/content.config.ts at the root of src, and the older location inside src/content/ is still honoured for projects that have not migrated:

// src/content.config.ts
import { defineCollection, reference } from 'astro:content';
import { glob } from 'astro/loaders';
import { z } from 'astro/zod';

const blog = defineCollection({
  loader: glob({ pattern: '**/*.{md,mdx}', base: './src/data/blog' }),
  schema: z.object({
    title: z.string(),
    description: z.string(),
    pubDate: z.coerce.date(),
    updatedDate: z.coerce.date().optional(),
    tags: z.array(z.string()).default([]),
    draft: z.boolean().default(false),
    author: reference('authors'),
  }),
});

const authors = defineCollection({
  loader: glob({ pattern: '**/*.json', base: './src/data/authors' }),
  schema: z.object({
    name: z.string(),
    email: z.string().email(),
    website: z.string().url().optional(),
  }),
});

export const collections = { blog, authors };

Two things in that file are worth pausing on. The loader decides where the data comes from and how it is parsed; the glob loader walks a directory for Markdown or MDX files, and a file loader does the same for JSON or YAML. Because the loader is a separate concern from the schema, a collection can hold files from somewhere other than the filesystem without changing how it is queried. The schema is expressed with Zod, whose validators compose: z.coerce.date() turns a date written in frontmatter into a real date object, .optional() makes a field optional, .default() fills in a value when the field is absent, and z.array(z.string()) constrains a list.

The older API declared the type of the collection rather than a loader, and read the files from a folder under src/content/:

// src/content/config.ts
import { defineCollection, z } from 'astro:content';

const blog = defineCollection({
  type: 'content',
  schema: z.object({
    title: z.string(),
    pubDate: z.coerce.date(),
  }),
});

export const collections = { blog };

Projects following the older pattern keep their Markdown in src/content/blog/ and the API below works the same way, so the rest of this chapter applies to both.

Querying a collection is done with a small set of functions imported from astro:content:

FunctionWhat it returns
getCollection(name, filter?)Every entry in a collection, optionally filtered by a predicate over the entry
getEntry(name, id)A single entry, looked up by its identifier
getEntries(references)Several entries at once, used after following a reference field
render(entry)The Content component for an entry, together with its headings

A list page sorts the entries and hands them to a template:

---
// src/pages/blog/index.astro
import { getCollection } from 'astro:content';
import BaseLayout from '../../layouts/BaseLayout.astro';

const posts = (await getCollection('blog', ({ data }) => !data.draft))
  .filter((post) => post.data.pubDate <= new Date())
  .sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf());
---

<BaseLayout title="Blog">
  <ul>
    {posts.map((post) => (
      <li>
        <a href={`/blog/${post.id}/`}>{post.data.title}</a>
        <time datetime={post.data.pubDate.toISOString()}>
          {post.data.pubDate.toDateString()}
        </time>
      </li>
    ))}
  </ul>
</BaseLayout>

A single entry page fetches one entry and renders its body. The render helper returns a component, so the markdown content is rendered as a child component rather than as a string:

---
// src/pages/blog/[id].astro
import { getEntry, render } from 'astro:content';
import BaseLayout from '../../layouts/BaseLayout.astro';

const entry = await getEntry('blog', Astro.params.id);
if (!entry) {
  return Astro.redirect('/blog');
}

const { Content, headings } = await render(entry);
---

<BaseLayout title={entry.data.title} description={entry.data.description}>
  <article>
    <h1>{entry.data.title}</h1>
    <Content />
  </article>

  <nav aria-label="On this page">
    <ul>
      {headings.map((heading) => (
        <li><a href={`#${heading.slug}`}>{heading.text}</a></li>
      ))}
    </ul>
  </nav>
</BaseLayout>

The filter argument on getCollection is where a draft flag or a date in the future is enforced, and doing it in one place means a page can never accidentally publish something that was meant to be held back. Because the schema guarantees the shape, the template does not need defensive checks: if description is present in the schema, it is present in the data, and if a field is optional the template is expected to handle its absence.

The same pattern scales to a documentation set. Declare one collection for the reference pages with a schema describing the title, the section, the order, and the API version, then let a single route render every entry. A second collection for the changelog, a third for the glossary, and each is still one file of configuration and one template. A documentation set that has to be checked for consistency, such as one where every page must declare the product version it applies to, gets that guarantee from the schema rather than from a review checklist.

The last piece worth knowing is how entries relate to one another. The reference helper in a schema turns a plain field into a typed link to an entry in another collection, and getEntries resolves a list of such references in one call. It means a changelog entry can point at the release notes that introduced a flag, and a glossary can link to the page that defines a term, with both links checked at build time instead of breaking silently.

Found an issue with this content?

Tell us what could be improved.