Understanding Astro Content Collections
by Astro Theme Switcher
astro content-collections tutorial
Astro Content Collections provide a powerful, type-safe way to manage content in your Astro project. Let’s explore how they work.
Why Content Collections?
Traditional approaches to managing content often involve:
- Reading files from the filesystem manually
- Parsing frontmatter without validation
- No type safety or autocomplete
- Potential runtime errors from missing fields
Content Collections solve all of these problems by:
- Centralized Configuration: Define your content schema in one place
- Type Safety: TypeScript types are generated from your schema
- Validation: Invalid content is caught at build time
- Developer Experience: Full autocomplete and IntelliSense support
How It Works
Content Collections use a simple directory structure:
src/content/
blog/
post-1.md
post-2.md
config.ts
The config.ts file defines the schema for each collection using Zod, a TypeScript-first schema validation library.
Querying Content
You can query your content using Astro’s built-in functions:
import { getCollection } from 'astro:content';
// Get all blog posts
const posts = await getCollection('blog');
// Filter and sort posts
const publishedPosts = (await getCollection('blog', ({ data }) => {
return data.pubDate <= new Date();
})).sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf());
Rendering Content
To render a post, you need to:
- Get the entry using
getEntry - Render the content using
render() - Display it in your template
import { getEntry } from 'astro:content';
const post = await getEntry('blog', 'post-slug');
const { Content } = await post.render();
Then in your template:
<h1>{post.data.title}</h1>
<Content />
Content Collections make managing blog content a breeze! 🎉