What are Content Collections?
Content Collections organize your content into typed, validated groups. Instead of manually loading markdown files, you define collections with schemas and let Astro handle the rest.Key Benefits: Type-safe frontmatter, automatic TypeScript types, content validation, and optimized image handling.
Setup
Create acontent.config.ts file in your src/ directory:
src/content.config.ts
Defining Collections
UsedefineCollection() to create a collection:
- Basic Collection
- With Images
- Multiple Collections
Schema Validation
Schemas use Zod for runtime validation:Image Schemas
Use theimage() helper for optimized images:
src/content/blog/post.md
Querying Collections
Get All Entries
UsegetCollection() to fetch all entries:
src/pages/blog/index.astro
Filter Entries
Filter with a callback function:Get Single Entry
UsegetEntry() to fetch a specific entry:
src/pages/blog/[id].astro
Rendering Content
Callrender() on an entry to get the content component:
The
Content component is the rendered markdown/MDX. headings contains the document outline.Dynamic Routes
Generate routes from collections:src/pages/blog/[...slug].astro
Loaders
Loaders determine where content comes from. Theglob() loader reads files from disk:
References Between Collections
Create relationships between collections:src/content.config.ts
Type Safety
Astro generates TypeScript types automatically:Implementation Details
From the source code atsrc/content/runtime.ts, collections use:
- Data Store: Content entries are stored in a global data store
- Schema Validation: Zod schemas validate entries at build time
- Type Generation: TypeScript types are auto-generated from schemas
Practical Examples
Blog with Categories
src/content.config.ts
src/pages/blog/category/[category].astro
Documentation with Sidebar
src/content.config.ts
src/components/DocsSidebar.astro
Best Practices
1
Define clear schemas
Use descriptive field names and provide defaults where appropriate.
2
Validate early
Let Zod catch errors at build time, not runtime.
3
Use TypeScript
Take advantage of auto-generated types for type safety.
4
Organize by collection
Group similar content together (blog, docs, authors).
5
Filter in queries
Filter collections at query time for flexibility.
Use enums
Define allowed values with
z.enum() for better validation.Reference related content
Use
reference() to create relationships between collections.Optimize images
Use the
image() helper for automatic image optimization.Default values
Provide sensible defaults to make frontmatter easier to write.
Learn More
Routing
Generate routes from collections
Layouts
Create layouts for your content