Mastering Astro Content Collections
Content Collections are one of Astro’s most powerful features for managing content with full type safety.
What are Content Collections?
Content Collections provide a structured way to organize your content (like blog posts, documentation, etc.) with automatic type checking and validation.
Setting Up Collections
Define your collections 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(),
pubDate: z.date(),
tags: z.array(z.string()),
}),
});
export const collections = { blog };
Querying Content
Use the getCollection function to fetch your content:
---
import { getCollection } from 'astro:content';
const posts = await getCollection('blog');
const sortedPosts = posts.sort(
(a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf()
);
---
{sortedPosts.map(post => (
<article>
<h2>{post.data.title}</h2>
<p>{post.data.description}</p>
</article>
))}
Rendering Content
Render MDX content with the render() method:
---
const post = Astro.props;
const { Content } = await post.render();
---
<article>
<h1>{post.data.title}</h1>
<Content />
</article>
Benefits
- Type Safety: Full TypeScript support
- Validation: Automatic schema validation
- Performance: Optimized content loading
- Developer Experience: Great IDE support
Conclusion
Content Collections make managing content in Astro a breeze. They provide structure, type safety, and excellent developer experience.
📚 Series: Astro Fundamentals
Part 3 of 3
Comments
Join the discussion and share your thoughts