Build a Static Blog with Astro: Full Walkthrough
A hands-on Astro 6 walkthrough: scaffold the project, define a typed content collection, render posts, add pagination and RSS, then build and deploy a static blog.
By Velloreth
A blog is the smallest useful test of a static site generator. It has one content type, a listing, individual pages, and an RSS feed. If a framework cannot make that pleasant, it will not make anything else pleasant either.
This walkthrough builds one from an empty directory with Astro 6, ending with a dist/ folder you can drop on any static host. Every command is real and every step has a check you can run.
What you need
| Requirement | Version | Check with |
|---|---|---|
| Node.js | 22.12.0 or newer (even-numbered releases) | node -v |
| npm | 10 or newer (ships with Node) | npm -v |
| A terminal and editor | anything | - |
Astro 6 dropped Node 18 and 20 entirely, and odd-numbered Node releases are not supported. If node -v prints something older, install an current LTS before continuing:
# with nvm, on macOS or Linux
nvm install 22
nvm use 22
Step 1: Scaffold the project
npm create astro@latest my-blog -- --template minimal --no-install --no-git --skip-houston
cd my-blog
npm install
The flags skip the interactive wizard so the result is reproducible. If you prefer the prompts, just run npm create astro@latest and answer them. Then verify:
npm run dev
Astro v6.x.x Ready in 412 ms
➜ Local: http://localhost:4321/
Open it, confirm the placeholder page loads, and stop the server with Ctrl+C. Nothing else in the starter matters; you are going to replace src/pages/index.astro anyway.
Step 2: Understand the layout
You will touch four files repeatedly:
my-blog/
├── src/
│ ├── content.config.ts # collection schema - edit once
│ ├── content/blog/ # your .md files live here
│ ├── layouts/Post.astro # the page chrome around a post
│ └── pages/
│ ├── index.astro # home / post listing
│ └── blog/[...slug].astro
├── astro.config.mjs
└── package.json
src/content.config.ts is the important one. Astro 6 does not infer anything about your Markdown: you declare where the files are and what shape their frontmatter must have, and the build validates every file against that declaration.
Step 3: Define the collection
Replace src/content.config.ts with a blog collection that has a real schema:
import { defineCollection, z } from 'astro:content';
import { glob } from 'astro/loaders';
const blog = defineCollection({
loader: glob({ base: './src/content/blog', pattern: '**/*.{md,mdx}' }),
schema: z.object({
title: z.string().min(3).max(120),
description: z.string().min(40).max(220),
pubDate: z.coerce.date(),
author: z.string().default('jiteshprakash'),
tags: z.array(z.string()).default([]),
featured: z.boolean().default(false),
}),
});
export const collections = { blog };
Two details worth naming:
z.coerce.date()turns the plain2026-04-08YAML string into a realDate, so you can sort and format it without a date library.z.string().min(40)on the description is a content rule, not a technical one. It forces you to write a summary on every post, which is what search results and social cards actually display.
A schema that is too loose saves you a minute today and costs you a broken page later.
Step 4: Write your first post
Create src/content/blog/hello-world.md:
---
title: "Hello World"
description: "The first post on my new Astro blog - how it was built and what I am planning to write about here."
pubDate: 2026-04-08
tags: [meta, first-post]
featured: true
---
This is the first post. It is deliberately short, because the point of this
file is to prove that the pipeline works end to end.
## Why this blog exists
Content collections give me a schema, and a schema gives me a build that
fails when a frontmatter field is missing.
Add a deliberately broken second file to see the safety net work. Create src/content/blog/broken.md with pubDate: not-a-date, then run:
npx astro build
[ERROR] InvalidData
src/content/blog/broken.md
pubDate: Expected date, received string
Fix it or delete the file. This is the whole argument for a typed collection: the mistake surfaces at build time, on your machine, instead of as a blank page in production.
The frontmatter contract
After Step 3, every post file has to satisfy this shape. Keeping it next to your editor while you write saves a failed build:
| Field | Type | Required | Rule |
|---|---|---|---|
title | string | yes | 3-120 characters |
description | string | yes | 40-220 characters |
pubDate | date | yes | YYYY-MM-DD, coerced to Date |
author | string | no | defaults to jiteshprakash |
tags | array | no | defaults to [] |
featured | boolean | no | defaults to false |
If you later add heroImage, updatedDate, or a seo block, add it to the schema at the same time. A field that exists in your Markdown but not in the schema is not part of post.data - you get undefined at render time, which is a worse failure than a build error because nothing stops you.
Step 5: Render a single post
Create the dynamic route src/pages/blog/[...slug].astro:
---
import { getCollection, render } from 'astro:content';
import Post from '../../layouts/Post.astro';
export async function getStaticPaths() {
const posts = await getCollection('blog');
return posts.map((post) => ({
params: { slug: post.id },
props: { post },
}));
}
const { post } = Astro.props;
const { Content, headings } = await render(post);
---
<Post
title={post.data.title}
description={post.data.description}
pubDate={post.data.pubDate}
headings={headings}
>
<Content />
</Post>
render(entry) is the Astro 6 API - the old entry.render() method is gone. It returns the <Content /> component plus a headings array extracted from your Markdown, which is enough to build a table of contents without parsing anything yourself.
The route is [...slug] rather than [slug] because the entry id can contain slashes if you organize posts into subfolders.
Now the layout, src/layouts/Post.astro:
---
interface Props {
title: string;
description: string;
pubDate: Date;
headings: { depth: number; slug: string; text: string }[];
}
const { title, description, pubDate } = Astro.props;
const formatted = pubDate.toLocaleDateString('en-CA', {
year: 'numeric', month: 'long', day: 'numeric',
});
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{title}</title>
<meta name="description" content={description} />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:type" content="article" />
</head>
<body>
<header><a href="/">My Blog</a></header>
<article>
<h1>{title}</h1>
<time datetime={pubDate.toISOString()}>{formatted}</time>
<slot />
</article>
</body>
</html>
<slot /> is where the Markdown lands. Everything around it is ordinary HTML with variables substituted - no template-string soup, no dangerouslySetInnerHTML.
Step 6: The listing page
Replace src/pages/index.astro:
---
import { getCollection } from 'astro:content';
const posts = (await getCollection('blog')).sort(
(a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf(),
);
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>My Blog</title>
</head>
<body>
<h1>My Blog</h1>
<ul>
{
posts.map((post) => (
<li>
<a href={`/blog/${post.id}/`}>{post.data.title}</a>
<p>{post.data.description}</p>
</li>
))
}
</ul>
</body>
</html>
post.id is the file path minus the extension, derived automatically by the glob loader. Sorting by valueOf() compares numeric timestamps - calling .getTime() inside a sort comparator works too, but valueOf() is the shorter version.
When the list grows past twenty or so posts, switch to built-in pagination instead of rewriting it yourself. Move the route to src/pages/blog/[...page].astro:
---
import { getCollection } from 'astro:content';
import Post from '../../layouts/Post.astro';
export async function getStaticPaths() {
const posts = (await getCollection('blog')).sort(
(a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf(),
);
return paginate(posts, { pageSize: 10 });
}
const { page } = Astro.props;
---
<h1>Posts</h1>
<ul>
{
page.data.map((post) => (
<li>
<a href={`/blog/${post.id}/`}>{post.data.title}</a>
</li>
))
}
</ul>
<nav>
{page.url.prev && <a href={page.url.prev}>Newer</a>}
<span>Page {page.current} of {page.lastPage}</span>
{page.url.next && <a href={page.url.next}>Older</a>}
</nav>
paginate() is provided by Astro in any page file - no import needed. It emits one route per page and hands you page.data, page.current, page.lastPage, and page.url.prev / page.url.next. Existing single-post routes stay untouched because they live at blog/[...slug].astro, not blog/[...page].astro.
Step 7: RSS at build time
npm install @astrojs/rss
Create src/pages/rss.xml.ts:
import rss from '@astrojs/rss';
import { getCollection } from 'astro:content';
export async function GET(context: { site: URL }) {
const posts = (await getCollection('blog')).sort(
(a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf(),
);
return rss({
title: 'My Blog',
description: 'Notes on building things with Astro and TypeScript.',
site: context.site,
items: posts.map((post) => ({
title: post.data.title,
description: post.data.description,
pubDate: post.data.pubDate,
link: `/blog/${post.id}/`,
})),
});
}
Set site in astro.config.mjs - RSS links are absolute and Astro derives them from that value:
export default defineConfig({
site: 'https://example.com',
});
Check it after a build: dist/rss.xml should exist and contain one <item> per post.
Step 8: Build and inspect
npx astro check && npx astro build
astro check validates your TypeScript and templates; it needs @astrojs/check and typescript, which the starter installs. Then look at what you actually shipped:
find dist -type f | head -20
du -sh dist
You get one HTML file per post, one for the listing, an rss.xml, and an assets folder. No server, no database, no runtime.
Preview the production build rather than trusting the dev server:
npx astro preview
Step 9: Deploy
Any host that serves static files works. Push to a Git repository and connect it, or upload the directory directly.
| Host | Connect how | Build command | Output |
|---|---|---|---|
| Cloudflare Pages | Git | npm run build | dist |
| Netlify | Git | npm run build | dist |
| GitHub Pages | Git + Actions | npm run build | dist |
| Any VPS | rsync/scp | run locally | dist/ |
For a bare server, the deploy is three commands:
npm run build
rsync -av --delete dist/ user@server:/var/www/blog/
Because the output is plain files, rollback is a re-sync from a previous Git tag. There is no container to rebuild.
Errors you will hit once
| Error | Cause | Fix |
|---|---|---|
Cannot find module 'astro:content' | Content config missing or misnamed | File must be src/content.config.ts, not src/content/config.ts |
InvalidData on a post | Frontmatter fails the Zod schema | Read the field name in the error, fix the .md file |
getStaticPaths returned nothing | Collection is empty or filtered to nothing | Check the glob base path and any draft filter |
Blank page at /blog/x/ | Route is [slug] but the id has slashes | Rename to [...slug].astro |
| RSS has no items | site is unset in astro.config.mjs | Set site, rebuild, check dist/rss.xml |
astro check fails but dev works | Types are stricter than the dev server | Run npx astro sync to regenerate content types |
That last one is worth memorizing: astro sync regenerates the TypeScript types for astro:content. After you change the schema, your editor may keep the old types until you run it - the build regenerates them automatically, but the editor does not.
What to add next
The blog above is complete and shippable. Everything after this is optional, in the order I would add it:
- A shared layout for the listing and home pages - you are currently repeating
<head>markup in two files. - Tags - a
src/pages/tags/[tag].astroroute built frompost.data.tags, usinggetStaticPathsto emit one page per tag. - Draft filtering - add
draft: z.boolean().default(false)to the schema and filter ingetCollection('blog', ({ data }) => !data.draft). - Reading time and a table of contents - the
headingsarray fromrender()already gives you the TOC; reading time is a word count over the raw Markdown. - Syntax highlighting - Astro has it built in via Shiki; set
markdown.shikiConfiginastro.config.mjs.
None of these change the architecture. That is the point of starting with a schema and two routes: the expensive decisions are already made, and the rest is adding pages.
The build you ran a few minutes ago is the same command your host runs on every push. If a post has a bad date, the deploy fails before anything changes in production - which is the quiet benefit you stop noticing after a week, right up until the first time it saves you.