Mastering Content Collections in Astro

Astro

Astro Content Collections provide a powerful way to manage your content with type safety and validation. Let’s explore how to use them effectively.

What are Content Collections?

Content Collections allow you to define schemas for your content, ensuring type safety across your entire application. They work with Markdown, MDX, JSON, YAML, and more.

Defining a Collection

Create src/content/config.ts:

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(),
    publishDate: z.coerce.date(),
    tags: z.array(z.string()),
    category: z.string(),
  }),
});

export const collections = { blog };

Creating Content

Create markdown files in src/content/blog/:

---
title: "My Post"
description: "Post description"
publishDate: 2024-01-01
tags: ["tag1", "tag2"]
category: "Category"
---

Content here...

Querying Collections

import { getCollection } from 'astro:content';

const posts = await getCollection('blog');

Filtering and Sorting

const publishedPosts = (await getCollection('blog', ({ data }) => {
  return data.publishDate <= new Date();
})).sort((a, b) => b.data.publishDate.valueOf() - a.data.publishDate.valueOf());

Benefits

  • Type Safety: Full TypeScript support
  • Validation: Zod schema validation
  • IntelliSense: Auto-completion in your editor
  • Performance: Optimized content loading

Content Collections are the recommended way to manage content in modern Astro projects. Start using them today!