RSS feed
An RSS feed is an XML file with a list of recent posts. Readers add its address to a feed reader and learn about new posts without visiting the site. In Astro the feed is built by the @astrojs/rss package: you give it the posts and it produces correct XML.
Installing
npm install @astrojs/rssThis is an ordinary package, not an integration, so the config does not change. The feed needs site in astro.config.mjs, set in the SEO lesson.
The feed file
A feed is an endpoint that returns XML. Create src/pages/rss.xml.js:
// src/pages/rss.xml.js
import rss from '@astrojs/rss';
import { getCollection } from 'astro:content';
export async function GET(context) {
const posts = await getCollection('blog', ({ data }) => !data.draft);
return rss({
title: "Anna's blog",
description: 'Posts about web development',
site: context.site,
items: posts.map((post) => ({
title: post.data.title,
description: post.data.description,
pubDate: post.data.pubDate,
link: `/posts/${post.id}/`,
})),
});
}Open http://localhost:4321/rss.xml and the browser shows XML with an <item> element for each post. The rss() function turns relative links into full ones using context.site.
Post fields in the feed
| Field | What it holds |
|---|---|
title | The post title |
description | A short description |
pubDate | The publication date, a Date object |
link | The post address on the site |
content | Optional: the full post text in HTML |
The fields match the collection schema, so nothing needs computing, only moving over.
Linking to the feed
For browsers and feed readers to find the feed on their own, add this to the <head> of the layout src/layouts/BaseLayout.astro:
<link
rel="alternate"
type="application/rss+xml"
title="Anna's blog"
href={new URL('rss.xml', Astro.site)}
/>A visible "RSS" link can go into the footer: <a href="/rss.xml">RSS</a>. It also fits the sidebar slot from the layouts lesson.
Common mistake
People name the file src/pages/rss.astro. Then Astro expects page markup rather than a GET function, and no feed appears. The feed file must be an endpoint: a .js or .ts extension, with the final address extension in the name, rss.xml.js.