Content Collections are one of Astro’s most powerful features for managing content. They provide type safety, validation, and a great developer experience for working with Markdown files.
What are Content Collections?
Content Collections allow you to organize and manage your content (like blog posts) with:
- Type Safety: Zod schemas ensure your frontmatter is correct
- Validation: Automatic validation of your content structure
- TypeScript Support: Full TypeScript support for your content
- Easy Querying: Simple API to fetch and filter content
Setting Up Content Collections
First, create a content/config.ts file:
import { defineCollection, z } from 'astro:content';
import { glob } from 'astro/loaders';
const blog = defineCollection({
loader: glob({ pattern: '**/*.md', base: './src/content/blog' }),
schema: z.object({
title: z.string(),
description: z.string(),
pubDate: z.coerce.date(),
tags: z.array(z.string()),
}),
});
export const collections = { blog };
Creating Blog Posts
With your collection defined, you can create Markdown files in src/content/blog/:
---
title: "My First Post"
description: "This is my first blog post"
pubDate: 2024-01-15
tags: ["astro", "blog"]
---
# My First Post
Content goes here...
Querying Content
You can query your content collections in your pages:
---
import { getCollection } from 'astro:content';
const posts = await getCollection('blog');
---
{posts.map(post => (
<article>
<h2>{post.data.title}</h2>
<p>{post.data.description}</p>
</article>
))}
Benefits
Content Collections provide:
- Type Safety: Catch errors at build time
- Better DX: Autocomplete and IntelliSense
- Validation: Ensure content follows your schema
- Flexibility: Easy to extend and customize
Start using Content Collections in your next Astro project!