In this article, I will explain how you can create an RSS feed for your Next.js application in XML and JSON format. So without further delay, let's get into it.
Table of Contents
what is RSS?
An RSS (Really Simple Syndication) feed is a file that contains a summary of updates from a website, often in the form of a list of articles with links.
In my case, I am creating an RSS feed for my blogs to show the latest blogs as the site updates. The user doesn't need to visit to check if there is an update or a new blog. RSS sends you the notification or shows the list of updates. You can use RSS Feed Reader chrome extension to manage your feed.
What do we need?
- We need all the blogs' data
- install the
feed
package - Create RSS Feed
Method-1
Getting the Blogs' data
I am assuming you already have your blog page where all the blogs are listed. I am using MDX for managing the blog content. You might be using the same or anything else that doesn't matter. The main thing is you need to have an array containing all the blogs.
As I am using the MDX, that's how I fetch all my blogs of mine.
// lib/posts.js
export function getAllPosts() {
const posts = getSlugs()
.map((slug) => {
return getFrontMatter(slug);
})
.filter((post) => post != null || post != undefined) // Filter post if it is not published
.sort((a, b) => {
if (new Date(a.date) > new Date(b.date)) return -1;
if (new Date(a.date) < new Date(b.date)) return 1;
return 0;
});
return posts;
}
The above function gets all the blogs by fetching all the slugs
and the for every slug it returns the frontMatter
of that blog and then sorted it in descending order by date, which contains information like title, publishedDate, excerpt, etc. Now we use this information to create the RSS feed.
Install the feed
package
It's very simple, you just have to install the package called feed
to create RSS. You can install it with npm
or yarn
, whatever you prefer.
yarn add feed
# or
npm i feed
Create RSS Feed
To generate the RSS feed we create a function called generateRssFeed
. You can change the name if you want.
import packages
First, we import all the important packages or functions
// lib/generateRssFeed.js
import fs from "fs";
import { Feed } from "feed";
import { getAllPosts } from "./posts";
Create a function
Creating a function called generateRssFeed
and we are exporting it, which I'll talk about later in this article.
// lib/generateRssFeed.js
export default async function generateRssFeed() {}
get the initial information
Now we add the following information in the above function such as all the blogs, today's date, and the author and the siteURL.
// lib/generateRssFeed.js
const posts = getAllPosts();
const siteURL = process.env.VERCEL_URL;
const date = new Date();
const author = {
name: "John Doe",
email: "example@gmail.com",
link: "https://twitter.com/<username>",
};
In the above code, I've used the process.env.VERCEL_URL
as the siteURL. You might be wondering why I used that. In my case, I am using vercel to host my website. So we need to pass the siteURL to the RSS. In the production or Preview in Vercel, it provides us the environment variable called VERCEL_URL
which is nothing but your site root URL. For example https://google.com
. We need the root URL for the production as well as the development phase because we need to check if our RSS is working or not. That's why I've chosen VERCEL_URL
as the environment variable. My .env.local
looks like this-
# .env.example
VERCEL_URL=http://localhost:3000
You don't need to define that in your production if you are also using the Vercel as a hosting platform. Otherwise, you can simply add your site root URL.
After that, we will create a feed
// lib/generateRssFeed.js
const feed = new Feed({
title: "Your Blog name",
description: "Your Blog description",
id: siteURL,
link: siteURL,
image: `${siteURL}/favicon.ico`,
favicon: `${siteURL}/favicon.ico`,
copyright: `All rights reserved ${date.getFullYear()}, Jatin Sharma`,
updated: date, // today's date
generator: "Feed for Node.js",
feedLinks: {
rss2: `${siteURL}/rss/feed.xml`, // xml format
json: `${siteURL}/rss/feed.json`,// json fromat
},
author,
});
The above code creates an RSS feed in XML
and JSON
format.
Add Blogs to the Feed
Now, as our feed is created, we just need to add all the blogs in that feed. To do that, we loop through the array of blogs and add the blog to the feed. The following code shows how you can do it.
// lib/generateRssFeed.js
posts.forEach((post) => {
const url = `${siteURL}/blog/${post.slug}`;
feed.addItem({
title: post.title,
id: url,
link: url,
description: post.excerpt,
content: post.excerpt,
author: [author],
contributor: [author],
date: new Date(post.date),
});
});
This code is straight forward and we just add the important data to the feed.
Write the RSS files in the public folder
After all this, we just need to make an xml
and json
file. The following code will create xml
and json
files for the RSS feed.
// lib/generateRssFeed.js
fs.mkdirSync("./public/rss", { recursive: true });
fs.writeFileSync("./public/rss/feed.xml", feed.rss2());
fs.writeFileSync("./public/rss/feed.json", feed.json1());
Now our work is almost completed. And our generateRssFeed.js
looks something like this -
// lib/generateRssFeed.js
import fs from "fs";
import { Feed } from "feed";
import { getAllPosts } from "./posts";
export default async function generateRssFeed() {
const posts = getAllPosts();
const siteURL = process.env.VERCEL_URL;
const date = new Date();
const author = {
name: "John Doe",
email: "example@gmail.com",
link: "https://twitter.com/<username>",
};
// Creating feed
const feed = new Feed({
title: "Your Blog name",
description: "Your Blog description",
id: siteURL,
link: siteURL,
image: `${siteURL}/favicon.ico`,
favicon: `${siteURL}/favicon.ico`,
copyright: `All rights reserved ${date.getFullYear()}, Jatin Sharma`,
updated: date, // today's date
generator: "Feed for Node.js",
feedLinks: {
rss2: `${siteURL}/rss/feed.xml`, // xml format
json: `${siteURL}/rss/feed.json`, // json fromat
},
author,
});
// Adding blogs to the rss feed
posts.forEach((post) => {
const url = `${siteURL}/blog/${post.slug}`;
feed.addItem({
title: post.title,
id: url,
link: url,
description: post.excerpt,
content: post.excerpt,
author: [author],
contributor: [author],
date: new Date(post.date),
});
});
// generating the xml and json for rss
fs.mkdirSync("./public/rss", { recursive: true });
fs.writeFileSync("./public/rss/feed.xml", feed.rss2());
fs.writeFileSync("./public/rss/feed.json", feed.json1());
}
Now, we just need to call this function to generate the feed as the data is updated. To do that we call this function inside the getStaticProps
in pages/index.js
because whenever our site is built and deployed, our RSS feed will be created and updated as well.
// pages/index.js
// first import that function
import generateRSS from "../lib/generateRssFeed";
export async function getStaticProps() {
// ........
await generateRSS(); // calling to generate the feed
// ........
}
I didn't want to push the RSS files to GitHub, because it is not necessary. That's why I put
/public/rss
in the.gitignore
.
That's it everything is done. Now if you are in the development then you can go to the localhost:3000/rss/feed.xml and if you are in the production then you can just simply go to https://yoursite.com/rss/feed.xml
. You will find the RSS in xml
format. In case you want to get the json
data just use https://yoursite.com/rss/feed.json
.
Method-2
Install rss
package
In the second method you need to install the rss
package through npm
or yarn
yarn add rss
# or
npm i rss
Generating RSS
To generate an RSS feed, you need to create a function the same as we did in the previous method.
// lib/generateRSS.js
import { writeFileSync } from "fs";
import { getAllPosts } from "./posts";
import RSS from "rss";
export default async function getRSS() {
const siteURL = "https://yourdomain.com";
const allBlogs = getAllPosts();
const feed = new RSS({
title: "Your Name",
description: "your description",
site_url: siteURL,
feed_url: `${siteURL}/feed.xml`,
language: "en",
pubDate: new Date(),
copyright: `All rights reserved ${new Date().getFullYear()}, Your Name`,
});
allBlogs.map((post) => {
feed.item({
title: post.title,
url: `${siteURL}/blogs/${post.slug}`,
date: post.date,
description: post.excerpt,
});
});
writeFileSync("./public/feed.xml", feed.xml({ indent: true }));
}
Call the function
As we did in the previous method we can call it inside the getStaticProps
in pages/index.js
// pages/index.js
// first import that function
import generateRSS from "../lib/generateRssFeed";
export async function getStaticProps() {
// ........
await generateRSS(); // calling to generate the feed
// ........
}
After applying this method you just need to visit the /feed.xml
and it'll give you the result. For example - https://youdomain.com/feex.xml
My RSS feed is live right now you can check it out.
Wrapping Up
If you enjoyed this article then don't forget to press ❤️ and Bookmark it for later use. If you have any queries or suggestions don't hesitate to drop them. See you.
You can extend your support by buying me a Coffee.😊👇
My Newsletter