Getting Started with Content Collections
How Astro content collections make blog post management type-safe.
Astro’s content collections give you a type-safe way to manage Markdown files. Define a schema in src/content/config.ts, and Astro validates every post’s frontmatter at build time.
Defining a Schema
import { defineCollection, z } from 'astro:content';
const blog = defineCollection({
schema: z.object({
title: z.string(),
pubDate: z.date(),
}),
});
If a post is missing a required field, the build fails with a clear error — not a runtime surprise.
Querying Posts
Use getCollection('blog') in any .astro page to get all posts as a typed array. Sort, filter, and paginate as needed.
const posts = (await getCollection('blog')).sort(
(a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf()
);