An Astro Zod schema describes what frontmatter every entry in a content collection must have. You add it as schema in defineCollection() inside src/content.config.ts, import z from astro/zod, and Astro validates every file at build time, failing with the file name and field when something is wrong, and generating TypeScript types for entry.data.
This guide covers the field types you’ll use most, image and reference fields, cross-field rules, transforms, and how to read the errors. Astro 7 bundles Zod 4.
Key Takeaways
- Import
zfromastro/zod. Importing it fromastro:contentis deprecated and goes away in Astro 8.- Use
z.coerce.date()for dates,.optional()for fields that may be missing, and.default()to fill gaps.- Pass a function,
schema: ({ image }) => z.object(...), to validate local cover images.reference('authors')links entries across collections and is checked at build time..refine()adds rules that involve more than one field, such asupdatedDateafterpubDate.
Why validate frontmatter at all
Frontmatter is hand-typed YAML. Without a schema, a typo like pubdate instead of pubDate silently produces a post with no date, and the first sign of trouble is a broken sort order or Invalid Date on the live site.
A schema moves those problems to build time. It also gives you autocompletion and type checking on post.data, which removes a whole category of undefined bugs from layouts. If you haven’t set up collections yet, the content collections guide covers the basics first.
A complete starter schema
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { glob } from 'astro/loaders';
import { z } from 'astro/zod';
const blog = defineCollection({
loader: glob({ pattern: '**/*.{md,mdx}', base: './src/content/blog' }),
schema: z.object({
title: z.string().min(5).max(70),
description: z.string().min(50).max(160),
pubDate: z.coerce.date(),
updatedDate: z.coerce.date().optional(),
author: z.string().default('Editorial team'),
category: z.enum(['Guides', 'News', 'Case studies']),
tags: z.array(z.string()).default([]),
draft: z.boolean().default(false),
canonical: z.url().optional(),
}),
});
export const collections = { blog };
A matching post’s frontmatter:
# src/content/blog/launch-checklist.md (frontmatter)
title: Our website launch checklist
description: The 25 checks we run before every website goes live, from redirects and sitemaps to Open Graph images.
pubDate: 2026-10-20
category: Guides
tags: [launch, seo]
author, draft and tags aren’t in the file, so the defaults fill them in. updatedDate and canonical stay undefined.
Common field types
| Need | Zod | Notes |
|---|---|---|
| Required text | z.string() |
Add .min() / .max() for length |
| Optional text | z.string().optional() |
Value is undefined when missing |
| Text with fallback | z.string().default('x') |
Never undefined in entry.data |
| Date | z.coerce.date() |
Accepts 2026-10-20 or full ISO strings |
| Fixed choices | z.enum(['a', 'b']) |
Typos fail the build |
| List | z.array(z.string()) |
YAML [a, b] or a dash list |
| Number | z.number().int().positive() |
For order, rating, price |
| Boolean | z.boolean() |
YAML true / false |
| URL | z.url() |
Zod 4 top-level format |
z.email() |
Zod 4 top-level format | |
| Nested object | z.object({ ... }) |
For SEO or hero blocks |
Zod 4 moved string formats to top-level functions, so z.url() and z.email() are preferred over the older z.string().url() chain, which still works but is deprecated in Zod 4.
Use z.coerce.date() rather than z.date(). YAML may parse 2026-10-20 as a date or leave a quoted value as a string, and coercion handles both. Once parsed, post.data.pubDate is a real Date, so sorting and formatting work directly.
Validating images in frontmatter
To check that a cover image exists and get its dimensions, pass a function to schema. Astro gives you an image() helper:
// src/content.config.ts (excerpt)
const blog = defineCollection({
loader: glob({ pattern: '**/*.md', base: './src/content/blog' }),
schema: ({ image }) =>
z.object({
title: z.string(),
cover: image().optional(),
coverAlt: z.string().optional(),
}),
});
# src/content/blog/launch-checklist.md (frontmatter)
title: Our website launch checklist
cover: ./images/launch-cover.jpg
coverAlt: A checklist on a laptop screen
The path is relative to the Markdown file. If the file doesn’t exist, the build fails. In a page, post.data.cover is image metadata you can pass straight to <Image src={post.data.cover} alt={post.data.coverAlt} />. The image in frontmatter tip covers remote images and fallbacks.
Linking collections with reference()
Authors are a classic case: you want each post to point at an author entry, not repeat their name and bio:
// src/content.config.ts (excerpt)
import { defineCollection, reference } from 'astro:content';
import { glob, file } from 'astro/loaders';
import { z } from 'astro/zod';
const authors = defineCollection({
loader: file('src/data/authors.json'),
schema: z.object({ name: z.string(), bio: z.string() }),
});
const blog = defineCollection({
loader: glob({ pattern: '**/*.md', base: './src/content/blog' }),
schema: z.object({
title: z.string(),
author: reference('authors'),
related: z.array(reference('blog')).default([]),
}),
});
export const collections = { authors, blog };
In frontmatter, write the id: author: ana. In a page, resolve it with getEntry():
---
// src/pages/blog/[id].astro (excerpt)
import { getEntry } from 'astro:content';
const { post } = Astro.props;
const author = await getEntry(post.data.author);
---
<p>By {author?.data.name}</p>
An unknown id fails the build, so you can’t publish a post credited to an author who doesn’t exist. The collection references tip shows getEntries() for arrays.
Rules across fields with refine()
Some rules involve more than one field. Add them with .refine():
// src/content.config.ts (excerpt)
const postSchema = z
.object({
title: z.string(),
pubDate: z.coerce.date(),
updatedDate: z.coerce.date().optional(),
cover: z.string().optional(),
coverAlt: z.string().optional(),
})
.refine((d) => !d.updatedDate || d.updatedDate >= d.pubDate, {
message: 'updatedDate must be on or after pubDate',
path: ['updatedDate'],
})
.refine((d) => !d.cover || Boolean(d.coverAlt), {
message: 'coverAlt is required when cover is set',
path: ['coverAlt'],
});
The path makes the error point at the right field. The second rule is a cheap way to enforce alt text on every cover image, which helps accessibility and image search.
Transforming values
Zod can clean data as it validates. A common one is normalizing tags so SEO, seo and Seo all become one tag page:
// src/content.config.ts (excerpt)
tags: z
.array(z.string())
.default([])
.transform((tags) => [...new Set(tags.map((t) => t.trim().toLowerCase()))]),
Every page that reads post.data.tags now gets clean, unique values. This pairs well with tag and category pages, where inconsistent casing would otherwise create duplicate URLs.
Keep transforms small and predictable. If you find yourself writing complex logic in a schema, move it into a helper in src/lib/ and call it from pages instead.
Reusing one schema across collections
Blogs often have several collections with the same shape, for example blog and tips. Define the schema once:
// src/content.config.ts (excerpt)
const postSchema = z.object({
title: z.string(),
description: z.string(),
pubDate: z.coerce.date(),
});
const blog = defineCollection({
loader: glob({ pattern: '**/*.md', base: './src/content/blog' }),
schema: postSchema,
});
const tips = defineCollection({
loader: glob({ pattern: '**/*.md', base: './src/content/tips' }),
schema: postSchema.extend({ difficulty: z.enum(['easy', 'medium']).default('easy') }),
});
.extend() adds fields without repeating the base. This site uses the same approach for its own blog and tips collections.
Reading validation errors
When a file breaks the schema, the build stops with an error titled “Content entry data does not match schema.” (or “Content entry frontmatter does not match schema.” for frontmatter-based entries). The message names the collection, the entry id, and each failing field with Zod’s explanation, for example a missing title or a category that isn’t one of the enum values.
Fix the file, or change the schema if the rule was wrong, and rerun. The frontmatter does not match schema fix walks through the most common causes. Run npx astro sync after editing the schema to refresh types without starting the dev server. Many Astro blog themes include a validated schema like the one above, and the Astro content docs explain where collections live in a theme project. For the full API, see the official content collections reference.
FAQ
Where do I import z from in Astro?
Import it from astro/zod: import { z } from 'astro/zod'. Importing z from astro:content still works in Astro 7 but is deprecated and scheduled for removal in Astro 8. Using astro/zod guarantees you get the Zod version Astro was built with.
Which version of Zod does Astro use?
Astro 7 uses Zod 4. That’s why string formats like z.url() and z.email() are top-level functions. Older tutorials that use z.string().url() still run, but those chained formats are deprecated in Zod 4.
How do I make a frontmatter field optional in Astro?
Add .optional() to the field, for example updatedDate: z.coerce.date().optional(). The value is undefined when the field is missing. Use .default(value) instead if you want a fallback value rather than undefined.
How do I validate dates in Astro frontmatter?
Use z.coerce.date(). It accepts YAML dates and ISO date strings and converts them to a JavaScript Date, so you can sort and format them in pages. Invalid values like 2026-13-45 fail the build.
Can I use TypeScript types from my content schema?
Yes. Astro generates types from the schema, available as CollectionEntry<'blog'> from astro:content. Use it to type props in components, such as interface Props { post: CollectionEntry<'blog'> }.