Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 37 ยท Projects and Practice

Project: Build a Blog with Content Collections

Build a complete Astro blog: a typed content collection, post and tag pages, reading time, RSS feed, sitemap and SEO tags, with runnable stand-ins.

Time to combine what you know into a real site. In this project you build a blog with Markdown posts, tag pages, an RSS feed, a sitemap and clean SEO tags. The Astro code is shown read-only (the real framework cannot run here); the logic behind each step has a runnable stand-in in JavaScript so you can see exactly what is computed.

What you will build

flowchart LR
  A["src/content/blog/*.md"] --> B["Collection schema<br/>(validates front matter)"]
  B --> C["/blog/ index"]
  B --> D["/blog/[slug]/ pages"]
  B --> E["/tags/[tag]/ pages"]
  B --> F["/rss.xml"]
  C --> G["Static HTML in dist/"]
  D --> G
  E --> G
  F --> G

Every page is generated at build time from the same validated data.

Step 1: Project layout

TEXT
src/
  content.config.ts
  content/blog/
    hello-astro.md
    why-islands.md
  layouts/
    Base.astro
    Post.astro
  components/
    PostCard.astro
    TagList.astro
  pages/
    index.astro
    blog/
      index.astro
      [...slug].astro
    tags/
      index.astro
      [tag].astro
    rss.xml.ts
    404.astro

Step 2: Define the collection

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

const blog = defineCollection({
  loader: glob({ pattern: '**/*.md', base: './src/content/blog' }),
  schema: ({ image }) =>
    z.object({
      title: z.string().max(80),
      description: z.string().min(50).max(160),
      pubDate: z.coerce.date(),
      updatedDate: z.coerce.date().optional(),
      draft: z.boolean().default(false),
      tags: z.array(z.string()).default([]),
      cover: image().optional(),
      coverAlt: z.string().optional(),
    }),
});

export const collections = { blog };

The schema is your contract. A post with a missing description or a mistyped date fails the build with the file name, instead of shipping a broken page.

A sample post:

MARKDOWN
---
title: "Why islands matter"
description: "Islands let a page stay static while small parts become interactive, which keeps JavaScript small and pages fast."
pubDate: 2026-03-09
tags: ["astro", "performance"]
---

Most of a page never changes after load...

Step 3: Helper functions

Keep queries in one module so every page filters drafts the same way:

TypeScript
// src/lib/posts.ts
import { getCollection } from 'astro:content';

export async function getPublishedPosts() {
  const posts = await getCollection('blog', ({ data }) => import.meta.env.DEV || !data.draft);
  return posts.sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf());
}

export function readingMinutes(text: string, wpm = 220) {
  const words = text.trim().split(/\s+/).length;
  return Math.max(1, Math.round(words / wpm));
}

Drafts show in dev but never in the production build.

Step 4: Post pages

ASTRO
---
// src/pages/blog/[...slug].astro
import { getPublishedPosts, readingMinutes } from '../../lib/posts';
import { render } from 'astro:content';
import Post from '../../layouts/Post.astro';

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

const { post } = Astro.props;
const { Content } = await render(post);
const minutes = readingMinutes(post.body ?? '');
---
<Post {...post.data} minutes={minutes}>
  <Content />
</Post>

Step 5: Tag pages

ASTRO
---
// src/pages/tags/[tag].astro
import { getPublishedPosts } from '../../lib/posts';

export async function getStaticPaths() {
  const posts = await getPublishedPosts();
  const tags = [...new Set(posts.flatMap((p) => p.data.tags))];
  return tags.map((tag) => ({
    params: { tag },
    props: { posts: posts.filter((p) => p.data.tags.includes(tag)) },
  }));
}
const { tag } = Astro.params;
const { posts } = Astro.props;
---
<h1>Posts tagged "{tag}"</h1>
<ul>{posts.map((p) => <li><a href={`/blog/${p.id}/`}>{p.data.title}</a></li>)}</ul>

Step 6: RSS and sitemap

Terminal
npx astro add sitemap
npm install @astrojs/rss
TypeScript
// src/pages/rss.xml.ts
import rss from '@astrojs/rss';
import { getPublishedPosts } from '../lib/posts';

export async function GET(context) {
  const posts = await getPublishedPosts();
  return rss({
    title: 'My Astro Blog',
    description: 'Notes about building fast sites',
    site: context.site,
    items: posts.map((p) => ({
      title: p.data.title,
      description: p.data.description,
      pubDate: p.data.pubDate,
      link: `/blog/${p.id}/`,
    })),
  });
}

Step 7: SEO in the layout

ASTRO
---
// in Base.astro
const { title, description, image } = Astro.props;
const canonical = new URL(Astro.url.pathname, Astro.site);
---
<title>{title}</title>
<meta name="description" content={description} />
<link rel="canonical" href={canonical} />
<link rel="alternate" type="application/rss+xml" title="Blog" href="/rss.xml" />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:type" content="article" />

Add structured data (JSON-LD) for articles if you want rich results, and give every page a unique title and description.

Try it: validate front matter like the schema

This stand-in imitates the build-time check, including coercion of dates and defaults for tags and drafts. Break a field to see the message.

JS Collection schema stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try it: tags, reading time and RSS from posts

The pure logic of steps 3 to 6: filter drafts, sort, group by tag, estimate reading time.

JS Blog data pipeline

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Extension ideas

  • Add pagination with paginate() in getStaticPaths.
  • Add "related posts" by counting shared tags.
  • Generate Open Graph images with an endpoint.
  • Add a search page (see the docs project next).
  • Deploy with the deployment lesson and add the final checklist.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main benefit of the collection schema?

    The schema validates every entry at build time and gives typed data in pages.
  2. 2. Why filter drafts in a shared helper?

    One function prevents a draft from leaking through a page you forgot to update.
  3. 3. What does getStaticPaths do for tag pages?

    Dynamic routes in static output need an explicit list of params to generate.
  4. 4. Which file creates /rss.xml?

    An endpoint named rss.xml.ts runs at build time and writes the feed file.

Summary

  • A blog is a typed collection plus a handful of generated routes: list, post, tags, feed.
  • Keep queries (draft filtering, sorting) in one helper.
  • getStaticPaths turns data into pages; endpoints produce RSS; the sitemap integration needs site.
  • Unique titles, descriptions and canonical URLs make the content findable.

Next: Project: A Portfolio with Interactive Islands