Mastering Astro Content Collections
1 min read
Mastering Astro Content Collections
Content collections are Astro’s way of managing and validating your markdown content with full TypeScript support.
Defining a Schema
Create a src/content.config.ts file to define your content schemas:
import { defineCollection, z } from 'astro:content';
const posts = defineCollection({ schema: z.object({ title: z.string(), description: z.string(), pubDate: z.coerce.date(), tags: z.array(z.string()), }),});
export const collections = { posts };Benefits of Content Collections
- Type Safety - Get autocomplete for frontmatter fields
- Validation - Build fails if content doesn’t match schema
- Automatic Types - TypeScript types are generated automatically
Querying Content
Use getCollection to query your content:
import { getCollection } from 'astro:content';
const posts = await getCollection('posts');const publishedPosts = posts.filter(post => !post.data.draft);This gives you full type safety when working with your content!