Understanding Content Collections in Astro π
Content Collections are one of Astroβs most powerful features for managing your content. They provide type-safe frontmatter validation, automatic slug generation, and seamless integration with your components.
Why Use Content Collections? π€
- Type Safety: Catch frontmatter errors before they reach production π‘οΈ
- Organized Structure: Keep your content neatly organized in the
src/content
directory ποΈ - Better Developer Experience: Get automatic TypeScript inference and IDE support π»
Content project structure ποΈ
src/
βββ content/
βββ blog/
βββ understanding-astro-layouts.md
βββ installing-astro.md
βββ styles-and-themes-in-astro.md
Getting Started π
First, create your blog posts in the content directory:
src/content/blog/understanding-astro-layouts.md
---
title: "Understanding Astro Layouts"
description: "Learn how to use layouts effectively in Astro"
pubDate: 2025-02-21
---
# Understanding Astro Layouts
Learn how layouts work in Astro and how to use them effectively...
Create your content configuration file:
src/content.config.ts
import { defineCollection, z } from 'astro:content';
const blog = defineCollection({
loader: glob({ pattern: "**/[^_]*.md", base: "./src/content/blog" }),
schema: z.object({
title: z.string(),
description: z.string(),
pubDate: z.date(),
author: z.string().optional(),
})
});
export const collections = { blog };
Using Collections in Components π§©
Hereβs how to query your collection:
src/pages/blog/[i].astro
---
import { getCollection } from 'astro:content';
const blogPosts = await getCollection('blog');
---
<ul>
{blogPosts.map((post) => (
<li>
<a href={`/blog/${post.id}`}>
{post.title} - {post.date}
</a>
</li>
))}
</ul>
Best Practices π
- Always define schemas for your collections π
- Use appropriate Zod validators for your data β
- Keep your content structure consistent π
- Use TypeScript for better type inference π
Conclusion π
Content Collections make it easier to manage and validate your content while providing a better developer experience. Start using them in your Astro projects today!