Getting Started with Astro Content Collections

• Inzimam Ul Haq
Hero image for Getting Started with Astro Content Collections

Content collections are one of Astro’s most powerful features for managing structured content like blog posts, documentation, or any other type of content that follows a consistent schema.

What are Content Collections?

Content collections allow you to define schemas for your content using TypeScript, providing type safety and validation for your content files. This is perfect for blog posts, documentation, or any structured data.

Setting Up a Blog Collection

First, create a src/content/config.ts file to define your collections:

import { defineCollection, z } from "astro:content";

const blogCollection = defineCollection({
  type: "content",
  schema: z.object({
    title: z.string(),
    description: z.string(),
    pubDate: z.date(),
    author: z.string().optional(),
    heroImage: z.string().optional(),
    tags: z.array(z.string()).optional(),
  }),
});

export const collections = {
  blog: blogCollection,
};

Creating Content Files

Create your blog posts as MDX or Markdown files in src/content/blog/. Each file should start with frontmatter that matches your schema:

---
title: "My Blog Post"
description: "A description of my post"
pubDate: 2024-11-09
author: "Your Name"
heroImage: "/path/to/image.jpg"
tags: ["tag1", "tag2"]
---

Using Content in Pages

Access your content in Astro pages using the getCollection function:

---
import { getCollection } from "astro:content";

const posts = await getCollection("blog");
const sortedPosts = posts.sort(
  (a, b) => b.data.pubDate.getTime() - a.data.pubDate.getTime(),
);
---

{
  posts.map((post) => (
    <article>
      <h2>{post.data.title}</h2>
      <p>{post.data.description}</p>
      <time>{post.data.pubDate.toLocaleDateString()}</time>
    </article>
  ))
}

Benefits of Content Collections

  • Type Safety: Full TypeScript support with auto-generated types
  • Validation: Automatic validation of your content against schemas
  • Performance: Optimized content loading and processing
  • Developer Experience: Excellent IntelliSense and error checking

Content collections make managing structured content in Astro a breeze!