A Deep Dive into Astro Content Collections
Content Collections are one of Astro's best features. Here's how to use them to build type-safe, organized content for your blog or documentation site.
If you’re building a content-heavy website with Astro, Content Collections are your best friend. They provide type safety, schema validation, and a clean API for querying your content — all with zero runtime cost.
What Are Content Collections?
Content Collections are Astro’s built-in way to organize and validate your Markdown, MDX, or JSON content. Instead of manually importing files and hoping the frontmatter is correct, Collections give you:
- Type-safe frontmatter with Zod schemas
- Automatic validation at build time
- Clean querying APIs via
getCollection()andgetEntry() - Slug generation from file names
Setting Up a Collection
First, create your collection config in src/content/config.ts:
import { defineCollection, z } from "astro:content";
const blog = defineCollection({
type: "content",
schema: z.object({
title: z.string(),
description: z.string(),
date: z.coerce.date(),
readingTime: z.string(),
tags: z.array(z.string()).optional(),
}),
});
export const collections = { blog };
Then place your Markdown files in src/content/blog/. Each file’s frontmatter will be validated against your schema at build time.
Querying Content
The API is wonderfully simple:
import { getCollection } from "astro:content";
// Get all posts, sorted by date
const posts = (await getCollection("blog")).sort(
(a, b) => b.data.date.valueOf() - a.data.date.valueOf(),
);
// Filter posts by tag
const devPosts = await getCollection("blog", ({ data }) => {
return data.tags?.includes("development");
});
Rendering Content
On your dynamic route page, render the content like this:
---
const { post } = Astro.props;
const { Content } = await post.render();
---
<article>
<h1>{post.data.title}</h1>
<Content />
</article>
Why This Matters
The beauty of Content Collections is that they bring the rigor of a CMS to simple Markdown files. You get validation, type safety, and organization without any external service or database.
For blogs, documentation sites, and portfolios, this approach is hard to beat. Your content lives in your repository, your schema is enforced at build time, and your queries are type-safe and fast.
It’s the simplicity of Markdown with the power of a structured content system. And that’s a beautiful combination.