Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 16, 2022 09:33 am GMT

How to add RSS feed in Next.js Blog

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

  • Table of Contents
  • what is RSS?
  • What do we need?
    • Getting the Blogs' data
    • Install the feed package
    • Create RSS Feed
    • import packages
    • Create a function
    • get the initial information
    • After that we will create a feed
    • Add Blogs to the Feed
    • Write the rss files in the public folder

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

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.jsexport 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# ornpm 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.jsimport 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.jsexport 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.jsconst posts = getAllPosts();const siteURL = process.env.VERCEL_URL;const date = new Date();const author = {  name: "John Doe",  email: "[email protected]",  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.exampleVERCEL_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.jsconst 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.jsposts.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 a xml and json file. The following code will create xml and json files for the RSS feed.

// lib/generateRssFeed.jsfs.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.jsimport 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: "[email protected]",    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 functionimport 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.

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.
buymecoffee

My Newsletter


Original Link: https://dev.to/j471n/how-to-add-rss-feed-in-nextjs-blog-34j1

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To