Data, content, and assets
Validate content data
Give content fields a schema so a missing title, invalid date, or wrong value fails before deployment.
8 minute lesson
A schema makes the assumptions in your templates executable. Add it beside the collection loader:
import { defineCollection } from "astro:content"
import { glob } from "astro/loaders"
import { z } from "astro/zod"
const notes = defineCollection({
loader: glob({ base: "./src/content/notes", pattern: "**/*.md" }),
schema: z.object({
title: z.string(),
description: z.string(),
publishedAt: z.coerce.date(),
topic: z.enum(["astro", "css", "javascript"]),
draft: z.boolean().default(false)
})
})
export const collections = { notes }
Astro validates entries as it loads the collection. A missing title, impossible topic, or malformed date stops the build close to the bad source instead of failing later inside a page.
Use required fields when every template needs the value. Use optional fields only for genuine variants, not as a way to avoid cleaning inconsistent data. Defaults are useful when an omitted value has one unambiguous meaning.
Break an entry deliberately: set topic: cooking, run the build, and read the error back to the exact field. Then restore it. A useful schema is strict enough to catch mistakes and accurate enough to describe real content.
Lesson completed