What is an RSS feed

RSS(RDF Site Summary or Really Simple Syndication) feed is an XML file for subscribers to fetch recently updated content. It is a specific page on a website(usually /rss.xml) which returns all, or part of a website’s content in a listed structured XML format.

Why do you need an RSS feed

RSS feed is an important part of any website that has frequent updates. With RSS, your subscribers can easily get your new update and have immediate interaction on it.

How to create rss feed in Next.js

We will do this work based on next-blog-starter

Create a rss.js file in the lib directory with the following codes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { BLOG_URL, BLOG_TITLE } from 'lib/constants'
import markdownToHtml from 'lib/markdownToHtml'

export const generateRssItem = async (post) => {
const content = await markdownToHtml(post.content ?? '')

return `
<item>
<guid>${BLOG_URL}/posts/${post.slug}</guid>
<title>${post.title}</title>
<description>${post.excerpt}</description>
<link>${BLOG_URL}/posts/${post.slug}</link>
<pubDate>${new Date(post.date).toUTCString()}</pubDate>
<content:encoded><![CDATA[$${content}]]></content:encoded>
</item>
`
}

export const generateRss = async (posts) => {
const itemList = await Promise.all(posts.map(generateRssItem))
return `
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
<channel>
<title>${BLOG_TITLE}</title>
<link>${BLOG_URL}</link>
<lastBuildDate>${new Date(posts[0].date).toUTCString()}</lastBuildDate>
<atom:link href="${BLOG_URL}" rel="self" type="application/rss+xml" />
${itemList.join('')}
</channel>
</rss>
`
}

Generate Rss Feed XML at building time

To do so, we just need to generate the xml file in getStaticProps which is called at building time and write the result of generateRss into the public directory.

1
2
3
4
5
6
7
8
9
10
export const getStaticProps = async () => {
const posts = getAllPosts(['title', 'date', 'slug', 'excerpt', 'content'])
const rss = await generateRss(posts)
fs.writeFileSync(path.join(process.cwd(), 'public', 'rss.xml'), rss)
return {
props: {
allPosts,
},
}
}

Start the server and visit localhost:3000/rss.xml you can fetch your rss feed right now.

Tip: Remember to include public/rss.xml in the .gitignore file.