Chuyển đến nội dung

Bài 16 · Content Collections and Markdown

Content Collections and Loaders

Organize content with Astro content collections: define collections in content.config.ts, validate frontmatter with Zod schemas and load files, JSON or APIs.

A blog with fifty posts quickly runs into mistakes: one file has pubdate, another has pubDate, a third forgets the title. A page that reads these fields shows undefined and nobody notices until a visitor does. Content collections fix this. You declare what a piece of content must look like, and Astro checks every entry at build time and gives you TypeScript types for the data.

A collection is a named group of similar items: blog, authors, docs, products. Each item is an entry.

Defining a collection

Collections are declared in src/content.config.ts. Each one has a loader, which says where the data comes from, and an optional schema, which says what shape it must have.

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

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

export const collections = { blog };

Then put files in src/content/blog/:

MARKDOWN
---
title: "Why islands matter"
description: "A short tour of partial hydration."
pubDate: 2026-03-02
tags: ["astro", "performance"]
---

Islands let you ship less JavaScript...

If you leave out description or write pubDate: tomorrow, the build stops with an error naming the file and the field. Cheap to fix, and caught before deployment.

Astro 5 introduced the Content Layer API described here, with src/content.config.ts and loaders. Older projects used src/content/config.ts and the folder structure itself as the collection definition. Newer Astro versions import z from astro/zod; check your version's documentation if the import above is not found.

A collection has two parts

Loader Where entries come from
Schema What each entry must look like
1 / 2

The schema with Zod

Schemas use Zod, a TypeScript-first validation library. The most useful building blocks:

Zod Meaning
z.string() A text value
z.number() A number
z.boolean() true or false
z.coerce.date() Converts strings like 2026-03-02 to a Date
z.array(z.string()) A list of strings
z.enum(["a", "b"]) One of fixed values
.optional() Allowed to be missing
.default(x) Value used when missing
.max(160), .min(3) Length limits
z.string().url() A valid URL

Astro also offers an image() helper in the schema function to validate image paths and import them as optimized assets:

TypeScript
schema: ({ image }) =>
  z.object({
    title: z.string(),
    cover: image(),
    coverAlt: z.string(),
  }),

Loaders

The loader decides where data comes from. Astro ships two built-in ones:

  • glob() loads many files that match a pattern (Markdown, MDX, JSON, YAML, TOML).
  • file() loads one file that contains many entries, such as a JSON array of authors.
TypeScript
import { file } from "astro/loaders";

const authors = defineCollection({
  loader: file("./src/data/authors.json"),
  schema: z.object({
    id: z.string(),
    name: z.string(),
    twitter: z.string().optional(),
  }),
});

Beyond files, a loader can be an inline function that fetches data from anywhere, such as a CMS or a REST API. It returns an array of objects with an id:

TypeScript
const products = defineCollection({
  loader: async () => {
    const response = await fetch("https://api.example.com/products");
    const data = await response.json();
    return data.map((p: { id: number; name: string; price: number }) => ({
      id: String(p.id),
      name: p.name,
      price: p.price,
    }));
  },
  schema: z.object({ name: z.string(), price: z.number() }),
});

You can also publish loaders as packages for CMS products. The loaded data is cached between builds and kept in a local data store, so rebuilds are fast.

Entry ids

For glob(), the entry id is derived from the file path (without extension), converted to a URL-friendly slug: src/content/blog/first-post.md has the id first-post. You can override it with a slug field in the frontmatter or by passing a generateId option to the loader. Ids become the URL parts in dynamic routes.

Stand-in: a schema validator

Zod does not run on this site, but the idea is easy to model. This stand-in implements string, date, array, optional and default rules, then validates three entries and reports errors the way a build would.

Node.js Stand-in: validating entries against a schema

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Stand-in: a glob loader

The glob() loader turns file paths into entries. This stand-in applies a pattern to a virtual file list and builds ids, the way the real loader populates the data store.

Node.js Stand-in: glob pattern to entries

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Common errors

  • "Collection does not exist": the name in getCollection("blog") must match a key in collections.
  • "Invalid frontmatter": a field fails its schema; the message shows which file and field.
  • Types not updating: run astro sync (the dev server does it automatically).
  • Empty collection: the base or pattern of the loader does not match your files.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Where are collections defined in Astro 5?

    defineCollection calls and the collections export live in src/content.config.ts.
  2. 2. What does the glob() loader do?

    glob({ pattern, base }) turns each matching file into an entry.
  3. 3. What happens when a Markdown file violates the schema?

    Validation errors surface at build time with the offending file and field.
  4. 4. How can you load data from a REST API into a collection?

    A loader can be an async function that fetches data and returns an array of entries.

Summary

  • A collection groups similar content; each item is an entry with an id and validated data.
  • Define collections in src/content.config.ts with a loader and a Zod schema.
  • glob() and file() are the built-in loaders; custom loader functions can pull from any API.
  • Invalid content fails the build with a clear message, and the data is fully typed.
  • Run astro sync if types look stale.

Next: Querying Collections

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.