Astro

Content collections

Content collections is Astro's typed way to manage Markdown, MDX, JSON, or YAML files as groups. Each collection has a schema, and bad data fails the build.

How it is measured

Define collections in src/content.config.ts with defineCollection, a loader such as glob, and a Zod schema. Query with getCollection or getEntry. Each entry has an id, data validated by the schema, and a body you can render.

Check it by breaking a file on purpose. Remove a required title from one post and run the build. The error names the file and the field.

Worked example

A cooking school has 214 recipe files. The schema requires title, a date, and servings as a number. One file has servings: "four", and the build stops with the file path and the type mismatch.

After the fix, the index page filters by tag in one call and sorts by date, with the types known in the editor. No one has to open 214 files to check.

How it differs

Content collections organize and validate content. MDX is one file format a collection can hold. Collections exclude the choice of syntax; MDX excludes any check that fields exist.

Common errors

Skipping the schema and getting runtime undefined values. Forgetting that dates arrive as strings unless you coerce them. Putting drafts in the same folder with no filter. Reading files directly with fs and bypassing collections. Using the old config location after upgrading.

In practice

Move your blog or docs into a collection and write a schema that fits what you actually use. Add a draft boolean and filter on it. Run the build after each content PR.

See also

Astro, MDX

Sources

Count this on a real site.

Watch my website