Add RSS feed to your Nuxt Content site
Easily add RSS feed to Nuxt content site to easily serve contents to the subscribers
RSS feeds can be useful for serving site's content to the subscribers. In this tutorial we are going to use Nuxt 3 and Nuxt Content v2.
Preparing the app
First of all, let’s create a fresh copy of Nuxt 3 app. If you already have an app, then skip this step.
Installing libraries
To add an RSS feed to our app, we’re going to use an npm
library called feed. Let’s install the library:
npm install feed
Generating feed
At this point, we should assume that we already have some content (blog posts, pages etc.) in our content/
directory. For this tutorial, we’re going to put some blog posts in markdown files in content/blog/
directory.
Now, let’s use the server routes feature of Nuxt to dynamically generate the RSS feed and feed entries. Create a file in the following directory: server/routes/rss.ts
this will enable a route /rss
for your app. Inside the rss.ts
file, export the defineEventHandler
function to define the route’s behavior. Also import feed
library and serverQueryContent
for querying the contents from our content/
directory:
import { serverQueryContent } from '#content/server'
import { Feed } from 'feed'
export default defineEventHandler(async (event) => {
})
Inside the defineEventHandler
, query the contents using serverQueryContent
and store them in docs
. Then, filter the contents based on your criteria and store them feedItems
; Here, we’re going to use filter to get blog posts from content/blog/
directory:
const docs = await serverQueryContent(event).find()
const feedItems = docs.filter((doc) => doc?._path?.startsWith('/blog/'))
Then, define the RSS feed attributes (feedOptions
) inside a Feed
object:
const host = "<https://yoursite.com>"
const siteName = "Your Name"
const feed = new Feed({
id: host,
copyright: `All rights reserved 2023, ${siteName}`,
title: siteName,
link: host,
language: 'en',
favicon: `${host}/favicon.ico`
})
Now we need to add feed items. We’ll loop through the contents of feedItems
and use addItem
method of feed
library to insert items in the RSS feed.
for (const doc of feedItems) {
feed.addItem({
title: doc.title ?? '-',
id: host + doc._path,
link: host + doc._path,
date: new Date(),
description: doc.description
})
}
We have our RSS feed object ready. To get the XML output, we’re going to use rss2()
method. Then, set the event’s response header for XML response type.
const content = feed.rss2()
event.node.res.setHeader('content-type', 'text/xml')
event.node.res.end(content)
For static hosting
For static hosting, we use nuxt generate
to generate static files for our Nuxt site. To include our /rss
route in the pre-rendered files, we have to tell nitro to prerender that route in nuxt.config.ts
file:
nitro: {
prerender: {
routes: ['/rss.xml']
}
},