Back to Tech Notes
Static Sites

Type-Safe Content with Astro Collections

  • Astro
  • Content Collections
  • Zod
  • Static Sites

Notes on Astro's content collections — why Zod-validated frontmatter catches mistakes at build time instead of in the browser, and how a glob loader replaces manual file reads.

Summary

Astro's content collections give Markdown frontmatter a real schema. A typo in a date or a missing field fails the build instead of quietly rendering wrong — the same discipline a compiler gives code, applied to content.

Why this mattered

Before collections, a content site’s frontmatter was just an object shape you hoped every file agreed with. A missing date field, or date: 2024-13-45, wouldn’t fail until a page tried to format it — usually the least helpful moment to find out.

Zod schemas turn frontmatter into a contract. content.config.ts defines what every entry must have, and astro dev or astro build refuses to run if a file breaks it.

const isoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);

const notes = defineCollection({
  loader: glob({ pattern: '**/*.md', base: './src/content/notes' }),
  schema: z.object({
    title: z.string(),
    date: isoDate,
    tags: z.array(z.string()).default([]),
  }),
});

The loader is the other half

glob() is what actually walks the content directory and hands each file to the schema. Older Astro versions inferred this from folder structure; the current loader API makes it explicit, which also means a collection’s source folder no longer has to match its exported name — useful the moment you rename a folder for clarity and don’t want every route to change with it.

What I’d tell past me

Treat the schema as documentation first, validation second. Reading content.config.ts should tell a new contributor exactly what a valid note looks like, without opening a single content file.