How to Generate an RSS Feed for Your Nuxt Content Site
This guide provides step-by-step instructions to create a server route that generates an RSS feed for your site.
>
- Para ler em português, clique aqui
This guide provides step-by-step instructions to create a server route that generates an RSS feed for your site.
>
If you're running a blog powered by Nuxt 3 and Nuxt Content v2, adding an RSS feed is a great way to let readers subscribe to your updates. In this guide, we'll walk you through creating a server route to generate an RSS feed for your site.
Note: This guide is based on a post originally published on Maciej Pędzich's blog, which is no longer available online. However, you can access it via the Web Archive.
First, install the feed
package, a simple RSS feed generator for Node.js:
npm install feed
For transforming the Nuxt Content body into valid HTML, install the hast-util-to-html
package:
npm install hast-util-to-html
In your Nuxt project, create a server/routes/rss.xml.ts
file to define the server route. This will handle the RSS feed generation.
import { Feed } from 'feed';
import { serverQueryContent } from '#content/server';
import { toHtml } from 'hast-util-to-html';
export default defineEventHandler(async (event) => {
const blogUrl = 'https://www.example.com'; // Replace with your site URL
const feed = new Feed({
id: 'rss',
title: 'Your Blog Title',
description: 'RSS feed for Your Blog',
link: blogUrl,
copyright: `2024-present Your Blog Title`,
});
const docs = await serverQueryContent(event).find();
const recursivelyPatchChildren = (node) => {
if (node.type === 'text') {
return node;
} else if (node.tag === 'code' && node.props.language) {
node.props.lang = node.props.language;
node.children = [{ type: 'text', value: node.props.code }];
delete node.props.language;
delete node.props.code;
}
node.tagName = node.tag;
node.properties = node.props;
node.children = node.children.map(recursivelyPatchChildren);
return node;
};
for (const doc of docs) {
doc.body.children = doc.body.children.map(recursivelyPatchChildren);
const content = toHtml(doc.body);
feed.addItem({
id: doc._id,
title: doc.title,
description: doc.description,
link: new URL(doc._path, blogUrl).href,
content,
});
}
appendHeader(event, 'Content-Type', 'application/xml');
return feed.rss2(); // Generate RSS feed
});
To make the RSS feed available as a static file, update your nuxt.config.ts
file to include pre-rendering:
export default defineNuxtConfig({
nitro: {
prerender: {
routes: ['/rss.xml'],
},
},
});
Feed
object is set up with metadata such as the blog title, description, and link.hast-util-to-html
.With these steps, you now have a fully functional RSS feed for your Nuxt Content-powered site. Happy coding!
This text is organic,
created naturally by a human.
It may have gone through grammatical corrections,
with or without AI assistance,
but the original essence remains intact.
Blogs are conversations.
Join the conversation via email