Astro Themes & Starters

Astro Content Collections Mastery: Schemas, References, and Loaders That Scale

21 November 2026 · Updated 28 November 2026 · 13 min read · by Yang Kai

Master Astro content collections: define strict schemas with Zod, relate entries with references, validate at build time, and use loaders for content that lives beyond Markdown files.

Template inside: Astro Content Collection Schema Template

Contents
  1. The short version
  2. What you need before you start
  3. Step 1: Define the collection in `src/content.config.ts`
  4. Step 2: Pick the right loader for the source
  5. Step 3: Write a schema that earns its keep
  6. Step 4: Relate entries with references
  7. Step 5: Query and render without the mess
  8. From collection to pages: routing with `getStaticPaths()`
  9. The collection schema template
  10. When content changes too fast for builds: live collections
  11. Migrating an existing collection without breaking the build
  12. Common mistakes
  13. How we researched this
  14. What to do next
  15. Learn more

One mistyped date in one Markdown file should not quietly break one page in production. With content collections, it fails the build instead — loudly, with the file and field named. That trade, a red build today over a broken page tomorrow, is the whole point of the feature.

This guide goes past the basic blog setup. It covers strict Zod schemas, references between collections, the loader system that lets content live outside your repo, and the querying patterns that stay readable at a few hundred entries.

Everything here follows the current Astro content collections documentation. This site’s own articles and directory listings are content collections, so the patterns below are the ones this project actually runs on — described as documented behaviour, not as test results.

The short version

Piece Where it lives What it does
Config file src/content.config.ts Defines every collection in one place
Loader Inside each defineCollection() call Fetches entries from files, a single data file, or a remote source
Schema Inside each defineCollection() call Validates every entry at build time and generates TypeScript types
Reference A schema field built with reference() Links an entry to an entry in another collection, checked at build time
Query API getCollection(), getEntry(), getEntries() Reads entries in pages and components, typed end to end

If you are still at the “what is Astro” stage, start with the introduction to Astro for prompt-driven builders and come back. This article assumes a working project.

What you need before you start

Run npx astro sync after changing the config file. It regenerates the TypeScript types for your collections so your editor and astro check see the new shape — until you run it, your editor may report errors against a schema you have already fixed, which is a confusing first hour with the feature.

Step 1: Define the collection in src/content.config.ts

In current Astro, all collections are defined in one file, src/content.config.ts, using defineCollection from astro:content. Older tutorials point at src/content/config.ts — that location stopped being read in Astro 5, and following an old tutorial is the single most common reason a new collection “does nothing.”

Each collection definition has two parts:

You export a single collections object at the bottom of the file. That export is what registers the collections with Astro; a collection that is defined but not exported does not exist as far as your pages are concerned.

Step 2: Pick the right loader for the source

Loaders are the Astro 5 change that matters most. A collection no longer has to mean “Markdown files in a folder.” The built-in loaders cover most projects:

Loader Source Typical use
glob() A directory of Markdown, MDX, Markdoc, or JSON files Articles, docs pages, case studies
file() One JSON, YAML, or TOML file holding many entries Authors, pricing tiers, small datasets
Custom loader Any API, CMS, or database you can fetch at build time Product catalogues, listings synced from elsewhere

The glob() loader takes a pattern and a base directory. Each file becomes an entry whose ID is generated from its file path relative to the base, slugified — so guides/getting-started.md becomes the ID guides/getting-started. You can override ID generation when your source has its own stable identifiers.

The file() loader reads a single file containing an array (or an object) of entries. Each entry needs an id field, or you supply a parser that shapes the data. It is the right tool for the small, hand-maintained datasets that otherwise end up as loose JSON imports with no validation.

A custom loader is an object with a load() function that fetches your source and returns entries, each with a unique ID and a data object. The entries still pass through your schema, so a CMS that suddenly renames a field fails your build instead of your homepage. Write one only when a real external source appears — the built-in loaders handle everything stored in the repo.

Step 3: Write a schema that earns its keep

A schema does three jobs at once: it documents what an entry is, it validates every entry at build time, and it gives you TypeScript types everywhere you query, so entry.data.pubDate is a real Date object rather than a string you hope parses.

Four habits separate schemas that scale from schemas that fight you:

One more tool worth knowing: the schema can be a function that receives an image() helper, which validates that a frontmatter field points at a real image file. That turns a renamed cover image into a build error too, and pairs with the image optimisation workflow — the schema checks the file exists, the Image component handles what ships.

Step 4: Relate entries with references

Real sites are not one flat list of posts. Articles have authors, listings have categories, case studies belong to products. Astro models this with reference() in the schema: a field whose value is the ID of an entry in another collection.

author: reference("authors"),
related: z.array(reference("articles")).default([]),

References are validated at build time. Point one at a misspelled author ID and the build fails, naming the entry — the same fail-early behaviour as the rest of the schema. At query time, the field holds a reference object (the collection name and ID), and you resolve it with getEntry() for one entry or getEntries() for an array, usually inside the page that renders the relationship.

Use references when the relationship is editorial — this article’s author, this product’s related listing — and keep plain strings when it is merely categorical, like tags. Over-referencing turns a pleasant Markdown workflow into a relational database you maintain by hand. The content sites that age best, including the ones in my comparison of Astro and Next.js for content-led projects, reference sparingly and on purpose.

Step 5: Query and render without the mess

getCollection() with a filter function covers most needs: published entries only, one category, sorted by date. Three patterns are worth standardising across a project:

To render a Markdown entry’s body, use the render() function from astro:content, which returns the Content component plus the entry’s headings and remark plugin metadata. Older tutorials call entry.render() instead; that method is the legacy API, and new code should use the imported function.

One distinction worth internalising: entries loaded from files of data (the file() loader, or JSON through glob()) have no body to render. They are pure data — query them, sort them, pass them as props, but do not expect a Content component. Content entries and data entries share the query API, not the rendering one.

These are small disciplines, but they compound. A site with a few hundred entries stays pleasant to build only because the boring parts are standardised.

From collection to pages: routing with getStaticPaths()

A collection earns its keep when it becomes pages. The standard pattern is a dynamic route — src/pages/blog/[...id].astro — whose getStaticPaths() maps every published entry to a page, using the entry’s id as the route parameter:

---
import { getCollection, render } from "astro:content";

export async function getStaticPaths() {
  const articles = await getCollection("articles", ({ data }) => !data.draft);
  return articles.map((entry) => ({
    params: { id: entry.id },
    props: { entry },
  }));
}

const { entry } = Astro.props;
const { Content } = await render(entry);
---

<h1>{entry.data.title}</h1>
<Content />

Three things in this pattern are deliberate. The draft filter lives inside getStaticPaths(), so a draft gets no route at all — it cannot leak as an unlinked page. The whole entry travels as a prop, so the template needs no second query. And the route parameter is the entry id, which is why the earlier warning about renaming files matters: the ID is the URL, and changing it is a redirect decision, not a tidy-up.

Index pages use the same collection differently: query once, sort with your named comparator, resolve any references the cards need with getEntries(), and render summaries from entry.data. Listing and detail pages reading from one validated source is the entire architecture — there is no second copy of the truth to drift.

The collection schema template

Copy this as the starting point for a new collection and adapt the fields, not the structure:

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

const articles = defineCollection({
  loader: glob({ pattern: "**/*.md", base: "./src/content/articles" }),
  schema: z.object({
    title: z.string().min(1),
    description: z.string().min(50).max(160),
    pubDate: z.coerce.date(),
    updatedDate: z.coerce.date().optional(),
    category: z.enum(["guides", "tutorials", "reviews"]),
    tags: z.array(z.string()).default([]),
    author: reference("authors").optional(),
    related: z.array(reference("articles")).default([]),
    draft: z.boolean().default(false),
    featured: z.boolean().default(false),
  }),
});

const authors = defineCollection({
  loader: glob({ pattern: "**/*.json", base: "./src/content/authors" }),
  schema: z.object({
    name: z.string(),
    role: z.string(),
    url: z.string().url().optional(),
  }),
});

export const collections = { articles, authors };

Note what the template encodes: length limits on the description (because it becomes a meta description), an enum for category (because free-text categories fragment), references for author and related entries, and defaults for every flag.

If you are choosing a theme rather than building from scratch, check whether it uses collections this rigorously. How I test Astro themes includes schema quality in the assessment, because it predicts how a theme ages.

When content changes too fast for builds: live collections

Build-time collections have one honest limit: the data is only as fresh as your last build. For content that changes constantly — live inventory, scores, availability — current Astro versions offer live collections, defined with defineLiveCollection() and a live loader, then read at request time with getLiveCollection() and getLiveEntry().

The trade is real. Live collections need on-demand rendering, which means an adapter and a running server (or serverless functions) instead of pure static files. For most content sites, a rebuild on publish is simpler and cheaper, and static output is what makes deploying Astro on Cloudflare Pages so undemanding. Reach for live collections when the data genuinely changes between builds, not as a default.

Migrating an existing collection without breaking the build

Schema changes on a live collection fail the build on every non-conforming entry, which is the point — but it means migrations should be staged:

  1. Add the new field as optional.
  2. Update the entries (a script, or a careful editing pass).
  3. Tighten the field to required once every entry complies.

Renaming a field is the same dance: add, migrate, remove. Trying to do it in one commit on a large collection is how afternoons disappear. If your content is arriving from another platform entirely, the staging mindset here pairs with the URL and export planning in migrating a WordPress site to Astro.

Common mistakes

How we researched this

This article follows the official Astro documentation for content collections — the guide and the astro:content API reference — checked November 2026, and describes the setup this site itself uses for its articles and listings. Where Astro versions differ (the config file move in Astro 5, the render() function replacing entry.render()), the article says so rather than presenting one version’s behaviour as universal.

Frequently asked questions

Where does the content config file live in current Astro? At src/content.config.ts. Older tutorials reference src/content/config.ts; Astro 5 moved it and made loaders part of every definition, so check which version a tutorial targets before copying its paths.

Where do I import z from? On Astro 5, z is re-exported from astro:content, as in the template above. The current documentation imports it from astro/zod — if you are starting a brand-new project on the newest Astro, follow the docs for your version.

Can one collection mix Markdown and remote data? A single collection has one loader, but nothing stops two collections — local articles and API-sourced listings — being merged at query time in a page. Keep sources in separate collections and combine them in code.

Do references update automatically if I rename an entry? No. The ID is derived from the file path, so renaming a file changes the ID and breaks references to it — and the build will tell you exactly where. That loud failure is preferable to a silent broken link.

Is a schema required, or can I skip it? You can define a collection without one, but you give up validation and typing — the two benefits that justify collections over plain file imports. For anything beyond a toy site, write the schema.

What to do next

Take your busiest collection and tighten one thing this week: an enum for its category, a length range on its description, or a reference replacing a free-text author name. Run the build and fix what it catches — that list is your content debt, made visible.

Collections pay off most when a site grows beyond a blog. Using Astro for documentation sites shows the same machinery carrying versioned, cross-referenced docs, and running Astro on Cloudflare covers what happens when the statically generated result meets a real host.

Learn more

Category: Astro Themes & Starters · Tags: #astro #tutorial #content

Next step: this article is part of Astro guides, which covers the full topic from first setup to advanced use.

Related guides