Skip to content

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

  1. Type Safety - Get autocomplete for frontmatter fields
  2. Validation - Build fails if content doesn’t match schema
  3. 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!


Written by

Farshad Akbari

Software engineer writing about Java, Kotlin TypeScript, Python, data systems and AI

Keyboard Shortcuts

Navigation

  • Open search ⌘K
  • Next article j
  • Previous article k

Actions

  • Toggle dark mode d
  • Toggle table of contents t
  • Show this help ?
  • Close modal Esc

Shortcuts are disabled when typing in inputs or textareas.