Skip to main content

Web frameworks · Beginner · 20 min

Build a fast content site with Astro 7 and content collections

By Padding · Updated 18 Nov 2026
Node.js 26.13 · Astro 7.4.13 · node:26 image

You will build a small blog with Astro 7.4, with a shared layout, Markdown posts checked against a Zod schema in a content collection, a page per post from getStaticPaths, an RSS feed, and a static build that ships no client JavaScript.

On this page

Astro is a framework for sites that are mostly content: blogs, documentation, marketing pages. It runs your components at build time and writes plain HTML files. Unless you ask for interactivity on a specific component, no JavaScript reaches the browser at all, which makes Astro pages fast on a low-end Android phone and cheap to load on prepaid data.

You will build Field Notes, a small blog for a developer meetup. Posts are Markdown files. A content collection reads them, checks every post's front matter against a schema, and gives your pages typed data, so a post with a missing description fails the build instead of shipping a broken page. At the end, npm run build writes a dist/ folder of HTML, CSS and an RSS feed that any static host can serve.

The tutorial assumes Node.js 26 from the Node.js install tutorial and works the same on Linux and macOS.

Step 1 · Create the project

create-astro copies an official starter into a new folder. The minimal template is the smallest: one page and a config file. The flags skip the questions (-y), the Git repository, the AI agent files and the animated mascot, and --no-install leaves the install to you so you can see it. The version is pinned so your files match this tutorial:

Bash
cd ~
npx -y create-astro@5.3.2 astro-notes-demo --template minimal --no-install --no-git --no-ai --skip-houston -y
cd astro-notes-demo
npm install

The first time you run an Astro command it prints a notice that Astro collects anonymous usage data. Run npx astro telemetry disable if you want to switch it off.

Check it worked

Bash
ls src/pages
cat astro.config.mjs
npm ls astro --depth=0

src/pages/ holds one file, index.astro. Every .astro or .md file in src/pages/ becomes a URL, so index.astro is /. astro.config.mjs calls defineConfig({}) with nothing set yet, and npm ls shows astro@7.4.x.

Step 2 · Run the development server

Start the dev server in your second terminal, from the astro-notes-demo folder, and leave it running while you work:

Bash
npm run dev

It prints a local address, http://localhost:4321/. In your first terminal, ask for the home page:

Bash
curl -s http://localhost:4321/ | grep -o '<title>Astro</title>'

Check it worked

The output is <title>Astro</title>, the starter page's title tag. Open http://localhost:4321/ in a browser and you see a page with the single heading "Astro". Open src/pages/index.astro, change the heading text and save: the browser updates on its own. Change it back before you go on.

Step 3 · Add a layout and an about page

An .astro file has two parts. Between the --- fences at the top is the component script: JavaScript or TypeScript that runs at build time, never in the browser. Below it is the template, which is HTML with {expressions}. Astro.props holds the attributes a parent passes in, and <slot /> marks where the parent's child content goes.

A layout is an ordinary component that holds the parts every page shares. Create one, and an about page that uses it:

Bash
mkdir -p src/layouts
cat > src/layouts/BaseLayout.astro <<'ASTRO'
---
interface Props {
  title: string;
  description?: string;
}

const { title, description = "Notes from a small developer community." } = Astro.props;
---

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
    <link rel="alternate" type="application/rss+xml" title="Field Notes" href="/rss.xml" />
    <meta name="description" content={description} />
    <title>{`${title} · Field Notes`}</title>
  </head>
  <body>
    <header>
      <a href="/" class="brand">Field Notes</a>
      <nav aria-label="Main">
        <a href="/">Posts</a>
        <a href="/about/">About</a>
        <a href="/rss.xml">RSS</a>
      </nav>
    </header>
    <main>
      <slot />
    </main>
    <footer>Built with Astro. No JavaScript required.</footer>
  </body>
</html>

<style is:global>
  body { max-width: 40rem; margin: 0 auto; padding: 1rem; font-family: system-ui, sans-serif; line-height: 1.6; }
  header { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 1rem; }
  nav { display: flex; gap: 1rem; }
  .brand { font-weight: 700; }
  footer { margin-top: 3rem; font-size: 0.875rem; }
</style>
ASTRO
cat > src/pages/about.astro <<'ASTRO'
---
import BaseLayout from "../layouts/BaseLayout.astro";
---

<BaseLayout title="About">
  <h1>About</h1>
  <p>Field Notes collects short write-ups from a developer meetup.</p>
</BaseLayout>
ASTRO

The Props interface types the layout's attributes, so a page that forgets title shows a type error in your editor. A plain <style> block in a component is scoped: Astro rewrites its selectors so they only match that component's markup. is:global turns that off, which is what you want for page-wide rules in a layout.

If your posts are written in French, Swahili or Yoruba, set lang on the <html> tag to fr, sw or yo, so screen readers pick the right voice and browsers offer the right translation.

Check it worked

Bash
curl -s http://localhost:4321/about/ | grep -o '<title>[^<]*</title>\|>About</h1>\|No JavaScript required'

The output is <title>About · Field Notes</title>, >About</h1> and the footer text: the page rendered inside the layout. The pattern matches only the end of the heading because the dev server adds data-astro-source-file attributes to the elements of your .astro templates, for its dev toolbar; npm run build leaves them out. In the browser, http://localhost:4321/about/ shows the header with its three links above the heading.

Step 4 · Define a posts collection with a schema

A content collection is a named set of entries with a loader that finds them and a schema that checks them. Collections live in src/content.config.ts. The glob loader reads every Markdown file under a folder; each file's name, without .md, becomes the entry's id. The schema is a Zod object, imported from astro/zod, that every post's front matter must match:

Bash
cat > src/content.config.ts <<'TS'
import { defineCollection } from "astro:content";
import { glob } from "astro/loaders";
import { z } from "astro/zod";

const posts = defineCollection({
  loader: glob({ pattern: "**/*.md", base: "./src/content/posts" }),
  schema: z.object({
    title: z.string(),
    description: z.string().max(160),
    pubDate: z.coerce.date(),
    tags: z.array(z.string()).default([]),
    draft: z.boolean().default(false),
  }),
});

export const collections = { posts };
TS

z.coerce.date() turns the 2026-10-03 you write in front matter into a JavaScript Date. .default([]) and .default(false) mean a post can leave out tags and draft, and your pages still get an array and a boolean. The 160-character limit on description keeps it short enough for search results and feed readers.

Now write three posts. The third is a draft, which the site will hide:

Bash
mkdir -p src/content/posts
cat > src/content/posts/first-meetup.md <<'MD'
---
title: Notes from our first meetup
description: What we covered at the first Field Notes meetup, and what comes next.
pubDate: 2026-10-03
tags: [community]
---

Twenty people came to the first meetup. We talked about **static sites** and why they suit slow connections.

## What is next

A workshop on content collections.
MD
cat > src/content/posts/images-on-prepaid-data.md <<'MD'
---
title: Smaller images for readers on prepaid data
description: Three habits that cut page weight for readers who pay for every megabyte.
pubDate: 2026-11-07
tags: [performance, images]
---

Every kilobyte costs a reader on a prepaid bundle. Resize images to the width they are shown at, prefer modern formats, and lazy-load anything below the fold.
MD
cat > src/content/posts/talk-ideas.md <<'MD'
---
title: Talk ideas for next year
description: A working list of talk ideas. Not ready to publish.
pubDate: 2026-11-15
draft: true
---

Still collecting ideas.
MD

To see the schema at work, add a post that leaves out description:

Bash
cat > src/content/posts/workshop-recap.md <<'MD'
---
title: Workshop recap
pubDate: 2026-11-12
---

Recap coming soon.
MD

Stop the dev server with Ctrl+C, then try a production build:

Bash
npm run build

The build stops with an error something like [InvalidContentEntryDataError] posts → workshop-recap data does not match collection schema, followed by description: Required. The dev server reports the same error in the terminal and the browser. Give the post its description; this replaces the whole file:

Bash
cat > src/content/posts/workshop-recap.md <<'MD'
---
title: Workshop recap
description: How the content collections workshop went, with the slides.
pubDate: 2026-11-12
tags: [community, astro]
---

Fourteen people built a blog in two hours. The slides are on the meetup page.
MD

Check it worked

Bash
npx astro sync
ls .astro

astro sync reads the collection, validates every post and prints that content was synced, with no error. It also writes TypeScript types for the collection into the hidden .astro/ folder, which is how your editor knows that post.data.pubDate is a Date. Start npm run dev again in your second terminal.

Step 5 · List the posts on the home page

getCollection("posts") returns every entry in the collection. Its optional second argument is a filter; here it drops drafts. Each entry has an id and a data object that already matches the schema, so data.pubDate is a Date you can sort on.

Dates need one decision. 2026-10-03 becomes midnight UTC, and formatting it in the build machine's own time zone can show 2 October on a machine west of Greenwich. A small helper that always formats in UTC avoids that:

Bash
mkdir -p src/utils src/components
cat > src/utils/formatDate.ts <<'TS'
export function formatDate(date: Date) {
  return date.toLocaleDateString("en-GB", { dateStyle: "long", timeZone: "UTC" });
}
TS
cat > src/components/PostCard.astro <<'ASTRO'
---
import type { CollectionEntry } from "astro:content";
import { formatDate } from "../utils/formatDate";

interface Props {
  post: CollectionEntry<"posts">;
}

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

<li class="post-card">
  <a href={`/posts/${post.id}/`}>{post.data.title}</a>
  <time datetime={post.data.pubDate.toISOString()}>{formatDate(post.data.pubDate)}</time>
  <p>{post.data.description}</p>
</li>

<style>
  .post-card { margin-bottom: 1.5rem; }
  .post-card a { display: block; font-weight: 700; }
  .post-card time { font-size: 0.875rem; }
  .post-card p { margin: 0.25rem 0 0; }
</style>
ASTRO
cat > src/pages/index.astro <<'ASTRO'
---
import { getCollection } from "astro:content";
import BaseLayout from "../layouts/BaseLayout.astro";
import PostCard from "../components/PostCard.astro";

const posts = (await getCollection("posts", ({ data }) => !data.draft)).sort(
  (a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf(),
);
---

<BaseLayout title="Posts">
  <h1>Latest posts</h1>
  <ul class="posts">
    {posts.map((post) => <PostCard post={post} />)}
  </ul>
</BaseLayout>
ASTRO

CollectionEntry<"posts"> is the type Astro generated from your schema. en-GB gives dates such as 7 November 2026; use your readers' locale, such as fr-SN or sw-KE, if the site is in another language.

Check it worked

Bash
curl -s http://localhost:4321/ | grep -o '<title>[^<]*</title>\|Notes from our first meetup\|Smaller images for readers on prepaid data\|Workshop recap\|Talk ideas for next year\|7 November 2026'

The output shows <title>Posts · Field Notes</title>, the three published titles and 7 November 2026, but not "Talk ideas for next year", because it is a draft. In the browser, the home page lists the newest post first. The post links lead to a 404 page for now.

Step 6 · Generate a page per post with getStaticPaths

A file name in square brackets is a dynamic route: src/pages/posts/[id].astro can answer /posts/anything/. In a static build Astro must know every URL in advance, so the page exports getStaticPaths(). It returns one object per page, with params to fill the brackets and props to hand the page its data.

render(post) turns the post's Markdown into a <Content /> component you place in the template:

Bash
mkdir -p src/pages/posts
cat > 'src/pages/posts/[id].astro' <<'ASTRO'
---
import { getCollection, render } from "astro:content";
import BaseLayout from "../../layouts/BaseLayout.astro";
import { formatDate } from "../../utils/formatDate";

export async function getStaticPaths() {
  const posts = await getCollection("posts", ({ data }) => !data.draft);
  return posts.map((post) => ({
    params: { id: post.id },
    props: { post },
  }));
}

const { post } = Astro.props;
const { Content } = await render(post);
---

<BaseLayout title={post.data.title} description={post.data.description}>
  <article>
    <h1>{post.data.title}</h1>
    <p>
      <time datetime={post.data.pubDate.toISOString()}>{formatDate(post.data.pubDate)}</time>
      {post.data.tags.length > 0 && <span> · {post.data.tags.join(", ")}</span>}
    </p>
    <Content />
  </article>
  <p><a href="/">Back to all posts</a></p>
</BaseLayout>
ASTRO

The single quotes around 'src/pages/posts/[id].astro' stop the shell treating the brackets as a pattern. The draft is filtered out here too, so no page is built for it.

Check it worked

Bash
curl -s http://localhost:4321/posts/first-meetup/ | grep -o '<title>[^<]*</title>\|<strong>static sites</strong>\|<h2 id="what-is-next">What is next</h2>'
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:4321/posts/talk-ideas/

The first command prints the post's title tag, the bold text and the ## What is next heading as an <h2> with an id that you can link to. The second prints 404: the draft has no page. In the browser, click a post on the home page and you land on its page, with "Back to all posts" at the bottom.

Step 7 · Add an RSS feed

An RSS feed lets readers follow the blog in a feed reader without visiting it. The official @astrojs/rss package builds the XML. Stop the dev server with Ctrl+C, then install it:

Bash
npm install @astrojs/rss@4.0.19

Feed links must be absolute, so Astro needs your site's address in the site option. Replace https://example.com with your own domain when you have one. This replaces the whole config file:

Bash
cat > astro.config.mjs <<'JS'
// @ts-check
import { defineConfig } from "astro/config";

// https://astro.build/config
export default defineConfig({
  site: "https://example.com",
});
JS

A file in src/pages/ that ends in .js or .ts and exports GET is an endpoint: at build time Astro calls it and writes what it returns to a file. rss.xml.js becomes /rss.xml:

Bash
cat > src/pages/rss.xml.js <<'JS'
import rss from "@astrojs/rss";
import { getCollection } from "astro:content";

export async function GET(context) {
  const posts = (await getCollection("posts", ({ data }) => !data.draft)).sort(
    (a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf(),
  );
  return rss({
    title: "Field Notes",
    description: "Notes from a small developer community.",
    site: context.site,
    items: posts.map((post) => ({
      title: post.data.title,
      description: post.data.description,
      pubDate: post.data.pubDate,
      link: `/posts/${post.id}/`,
    })),
  });
}
JS

Start npm run dev again.

Check it worked

Bash
curl -s http://localhost:4321/rss.xml | grep -o '<item><title>[^<]*</title>\|<link>https://example.com/posts/[^<]*</link>'

The output lists the three published posts, newest first, each with a full link starting https://example.com/posts/. The draft is not in the feed. Paste http://localhost:4321/rss.xml into a browser to see the raw XML.

Step 8 · Build the static site and preview it

Stop the dev server with Ctrl+C, then build:

Bash
npm run build
find dist -type f | sort

The build prints each route it generates and ends with Complete!. dist/ holds index.html, about/index.html, one index.html per published post under posts/, rss.xml and the favicons. Each page is a finished HTML file; small stylesheets are inlined into the page and larger ones go into dist/_astro/.

Now count the JavaScript files and script tags in the output:

Bash
find dist -name '*.js' | wc -l
grep -rl '<script' dist || echo "no script tags"

The first command prints 0 and the second prints no script tags. Every page works with JavaScript switched off, because there is no JavaScript. When one component needs to be interactive, Astro ships the code for that component only; that is the next tutorial.

npm run preview serves dist/ exactly as a static host would. Start it in your second terminal:

Bash
npm run preview

Check it worked

Bash
curl -s http://localhost:4321/ | grep -o '<title>[^<]*</title>'
curl -s http://localhost:4321/posts/workshop-recap/ | grep -o '<h1>[^<]*</h1>'

The output is <title>Posts · Field Notes</title> and <h1>Workshop recap</h1>, served from the files in dist/. In the browser, open http://localhost:4321/, open the developer tools' Network panel and reload: the page loads HTML, a favicon and nothing else. Copy dist/ to any static host, or follow the Cloudflare Pages tutorial with npm run build as the build command and dist as the output folder.

Step 9 · Clean up

Stop the preview server with Ctrl+C. If you want to keep the project for the next tutorial, stop here. Otherwise remove it:

Bash
cd ~
rm -rf ~/astro-notes-demo

Check it worked

ls ~/astro-notes-demo reports No such file or directory, and curl http://localhost:4321/ fails to connect. Node.js stays installed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.