Skip to main content

Overview

Astro provides powerful content management capabilities through Content Collections, allowing you to organize, validate, and query your content with full TypeScript support.

Content Collections

Content Collections are the recommended way to manage content in Astro. They provide type-safety, validation, and optimized queries for your Markdown, MDX, and data files.

Setting Up a Collection

1

Create the content directory

Create a src/content/ directory and add a subdirectory for your collection:
2

Define the collection schema

Create src/content.config.ts to define and validate your content:
src/content.config.ts
3

Query your content

Use the type-safe getCollection() function to retrieve your content:
src/pages/blog/index.astro

Dynamic Routes with Collections

Generate pages dynamically from your content using getStaticPaths():
src/pages/blog/[...slug].astro

Frontmatter

Frontmatter allows you to add metadata to your Markdown and MDX files using YAML syntax.

Basic Frontmatter

src/content/blog/my-post.md

Accessing Frontmatter

When using Content Collections, frontmatter is available through the data property:

Content Loaders

Content Collections support multiple loader types for flexible content sources.
Load content from your filesystem:
src/content.config.ts
Organize different content types with separate collections:
src/content.config.ts

Schema Validation

Use Zod schemas to validate and type-check your content.

Common Schema Patterns

String Fields

Numbers & Dates

Optional Fields

Images

Custom Validation

Add custom validation logic:
src/content.config.ts

Filtering and Sorting

Query and transform your content with JavaScript:
src/pages/blog/index.astro

Working with MDX

MDX allows you to use JSX components in your Markdown content.

Setup

astro.config.mjs

Using Components in MDX

src/content/blog/using-mdx.mdx

CMS Integrations

Astro works with headless CMS platforms for content management.

Contentful

Fetch content from Contentful’s API and render it in your Astro pages.

Sanity

Use Sanity’s GROQ queries to pull structured content into Astro.

Strapi

Connect to your Strapi backend API for content management.

WordPress

Use WordPress as a headless CMS via the REST or GraphQL API.

Example: Fetching from a Headless CMS

src/pages/posts/[slug].astro

Best Practices

1

Use Content Collections

Always prefer Content Collections over manual file parsing for better type safety and performance.
2

Validate Your Schema

Define strict schemas to catch content errors at build time rather than runtime.
3

Organize Collections Logically

Create separate collections for different content types (blog, docs, products, etc.).
4

Optimize Images

Use the image() schema helper to ensure images are optimized automatically.