Astro Content Collections Quick Reference

Written

Quick reference for Astro’s Content Collections API.

Setup (Astro 5+)

// src/content.config.ts
import { defineCollection, z } from 'astro:content';

const blog = defineCollection({
  type: 'content', // 'content' for MD/MDX, 'data' for JSON/YAML
  schema: z.object({
    title: z.string(),
    date: z.coerce.date(), // coerce converts strings to Date
    tags: z.array(z.string()).default([]),
    draft: z.boolean().default(false),
  }),
});

export const collections = { blog };

Querying

---
import { getCollection, getEntry } from 'astro:content';

// Get all entries (optionally filtered)
const posts = await getCollection('blog', ({ data }) => !data.draft);

// Get a single entry by ID
const post = await getEntry('blog', 'my-post-slug');

// Sort by date
const sorted = posts.sort((a, b) => b.data.date.valueOf() - a.data.date.valueOf());
---

Rendering

---
import { render } from 'astro:content';

const { Content, headings } = await render(post);
// headings: { depth, slug, text }[]
---

<Content />

Static Paths

---
export async function getStaticPaths() {
  const posts = await getCollection('blog');
  return posts.map((post) => ({
    params: { slug: post.id },
    props: { post },
  }));
}

const { post } = Astro.props;
---

TypeScript Types

import type { CollectionEntry } from 'astro:content';

type BlogPost = CollectionEntry<'blog'>;
// blog.data is fully typed from the schema

File Structure

src/
├── content.config.ts   ← schema definitions
└── content/
    ├── blog/
    │   └── my-post.md
    └── notes/
        └── my-note.md