Understanding Content Collections in Astro
Deep dive into Astro's Content Collections API and learn how to organize your Markdown content with type safety.
Understanding Content Collections in Astro
Content Collections are one of Astro’s most powerful features for managing content. They provide type safety, validation, and a clean API for querying your content.
What Are Content Collections?
A content collection is a group of related content entries (like blog posts) that share a common structure. Astro validates your content against a schema you define.
Defining a Collection
Create a content.config.ts file in your src directory:
import { defineCollection } from "astro:content";
import { glob } from "astro/loaders";
import { z } from "astro/zod";
const blog = defineCollection({
loader: glob({ pattern: "**/*.md", base: "./src/data/blog" }),
schema: z.object({
title: z.string(),
description: z.string(),
pubDate: z.coerce.date(),
}),
});
export const collections = { blog };
Querying Collections
Use getCollection() to fetch all entries:
import { getCollection } from "astro:content";
const posts = await getCollection("blog");
Benefits
- Type Safety: Full TypeScript support for your content
- Validation: Catch errors at build time
- Performance: Optimized for large content libraries
- Flexibility: Works with Markdown, MDX, JSON, and more
Content Collections make managing large content libraries a breeze!