Getting Started with Astro Content Collections
Content Collections are one of Astro’s most powerful features. They allow you to organize your Markdown and MDX content into typed, validated collections with schemas defined in Zod. This means you get TypeScript autocompletion, runtime validation, and a clean API for querying your content.
Why Content Collections?
Before Content Collections, managing Markdown content in Astro required manual slug handling and frontmatter parsing. You had to rely on Astro.glob() and type assertions. Content Collections solve these problems by providing:
- Type safety: Define schemas for your frontmatter with Zod and get full TypeScript support
- Validation: Invalid frontmatter is caught at build time, not in production
- Querying: Use the
getCollection()andgetEntry()APIs to fetch content with confidence - Organization: Content is organized into named directories under
src/content/
Setting Up Your First Collection
To create a content collection, you need a content.config.ts (or .mts) file at the root of your src/ directory. This file defines your collections and their schemas:
import { defineCollection, z } from 'astro:content';
const blog = defineCollection({
type: 'content',
schema: z.object({
title: z.string(),
description: z.string(),
pubDate: z.coerce.date(),
tags: z.array(z.string()).default([]),
}),
});
export const collections = { blog };
Then, place your Markdown files in src/content/blog/ and they’ll automatically be part of the blog collection.
Querying Collections
In your Astro pages, you can query collections using the generated types:
import { getCollection } from 'astro:content';
const allPosts = await getCollection('blog');
This returns an array of collection entries, each with a slug, data (typed frontmatter), and body (raw Markdown content). You can also filter entries:
const publishedPosts = await getCollection('blog', ({ data }) => {
return !data.draft;
});
Content Collections make it incredibly easy to build blogs, documentation sites, portfolios, and any content-heavy website with full type safety and developer confidence.