Blog Article

we are committed to nurturing young minds and fostering a love for learning

Astro Content Collections: A Practical Guide

6/5/2024 by Bob Smith
Astro Content Collections: A Practical Guide

Astro Content Collections are a powerful feature that let you organize and validate your content using TypeScript schemas. They make it easy to build blogs, documentation, and other content-driven sites with confidence.

Why Use Content Collections?

Getting Started

  1. Define your collection in src/content/config.ts:

    import { defineCollection, z } from "astro:content";
    
    const blog = defineCollection({
      schema: z.object({
        title: z.string(),
        pubDate: z.date(),
        description: z.string(),
        author: z.string().optional(),
        cover: z.string().optional(),
        tags: z.array(z.string()).optional(),
        draft: z.boolean().optional(),
      }),
    });
    
    export const collections = { blog };
  2. Add Markdown files to your collection folder:

    src/content/blog/my-first-post.md
  3. Query your collection in Astro pages:

    import { getCollection } from "astro:content";
    const posts = await getCollection("blog");

Tips

Content Collections are a game-changer for Astro projects. Try them out in your next site!

astro content guide