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
Create the content directory
Create a
src/content/ directory and add a subdirectory for your collection:Define the collection schema
Create
src/content.config.ts to define and validate your content:src/content.config.ts
Dynamic Routes with Collections
Generate pages dynamically from your content usinggetStaticPaths():
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 thedata property:
Content Loaders
Content Collections support multiple loader types for flexible content sources.File-based Loader (Glob)
File-based Loader (Glob)
Load content from your filesystem:
src/content.config.ts
Multiple Collections
Multiple Collections
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
Use Content Collections
Always prefer Content Collections over manual file parsing for better type safety and performance.
Validate Your Schema
Define strict schemas to catch content errors at build time rather than runtime.
Organize Collections Logically
Create separate collections for different content types (blog, docs, products, etc.).