Skip to content

Engineering

Astro Content Collections: Type-Safe Content

5 min read
Team collaborating with sticky notes on a wall

Static blogs have a recurring problem: Markdown files without structure. A frontmatter field is missing, a date has the wrong format, an image path points nowhere. You only notice at runtime — or never.

Content Collections solve this

Astro Content Collections bring schema validation to the content layer. You define a schema with Zod, and Astro validates every Markdown file at build time:

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

const blog = defineCollection({
  type: 'content',
  schema: z.object({
    title: z.string(),
    description: z.string(),
    date: z.date(),
    image: z.string(),
    draft: z.boolean().default(false),
  }),
});

If a required field is missing, the build fails. With a clear error message, not a cryptic runtime error.

Type-safe queries

getCollection() returns typed objects. No any, no guessing:

import { getCollection } from 'astro:content';

const posts = await getCollection('blog', ({ data }) => {
  return import.meta.env.PROD ? data.draft !== true : true;
});

The filter callback is elegant: in development you see all posts including drafts. In production, only the published ones.

Rendering content

The render API is a top-level import. Instead of entry.render(), you import render directly:

import { render } from 'astro:content';

const { Content } = await render(post);

The Content object is an Astro component you can drop directly into your template: <Content />.

Dynamic routes

For individual blog post pages, use getStaticPaths():

export async function getStaticPaths() {
  const posts = await getCollection('blog');
  return posts.map((post) => ({
    params: { slug: post.id.replace(/\.mdx?$/, '') },
    props: { post },
  }));
}

Important: post.id includes the file extension (.md). The extension must be stripped for clean URLs.

Why not a CMS?

Content Collections are the right choice when:

  • Your content lives in the repo — versioned, reviewable, alongside the code
  • Your team knows Git — no extra tool, no login, no dashboard
  • Performance matters — no API call at runtime, everything resolved at build time

For editorial teams with frequent updates, a headless CMS is a better fit. For technical blogs and documentation, Content Collections win.

Conclusion

Astro Content Collections make Markdown content type-safe and build-time validated. No runtime errors, no missing titles, no wrong date formats. The schema defines the contract, Zod enforces it.