Back

Understanding Content Collections in Astro

February 20, 2025

2 min read

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? πŸ€”

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 πŸ…

  1. Always define schemas for your collections πŸ“‘
  2. Use appropriate Zod validators for your data βœ…
  3. Keep your content structure consistent πŸ“‚
  4. 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!