SB

How to add RSS feed to Next.js site

July 28, 2021

-- views

table of contents

Recently, I found myself needing to add an RSS Feed to my personal website. After a bit of research, I found a very simple way to add this file using a package provided on npm for this specific use. So, I decided to create a quick guide in case you are also in need of creating this file, without writing XML manually.

Needless to say, this is by far not the only way, there are other packages and other methods.

Without further delay, let’s get to it.

What is an RSS Feed

In case you want to know what is an RSS Feed keep reading here. But, if you already know about this, then you probably would want to go direct to the guide in the next section.

Using a very simple definition an RSS (Really Simple Syndication) feed is a summary file that allows users and applications to access the website content in an easier way. Normally, RSS formats are specified using a generic XML file. Then, this information can be used by other browsers and applications to keep track of the website information.

For this quick guide, and in order to make the process simpler, we will not write XML manually. Instead, we’ll take advantage of an npm package created for this purpose. You can read more about this package here.

Let’s create an RSS Feed for a Next.js Project

First, we need to install the rss package we’re going to use:

npm i -D rss

Also, in case that your content is stored in markdown files, you’ll probably need a gray-matter parser. For this example I’m using the front-matter package:

npm i -D gray-matter

Now, create a new JavaScript file, this will be the file where we’re going to write our script. You can save it where you want (your project root could be a good idea).

const fs = require('fs');
const path = require('path');
const RSS = require('rss');
// create basic rss feed with high level data
// You can add more options (check the package github page)
const feed = new RSS({
    title: 'Your title here',
    description: 'Your description here',
    feed_url: `https://example.com/rss.xml`,
    site_url: `https://example.com`,
    managingEditor: 'Your name',
    webMaster: 'Your name',
    copyright: `${new Date().getFullYear()} your-name`,
    language: 'en',
    pubDate: new Date().toLocaleString(),
    ttl: '60'
});
 
// generate the xml to send to clients
const xml = feed.xml();
// Write file to public directory
// this is where next js looks for static files
fs.writeFileSync(path.resolve(__dirname, 'public') + '/rss.xml', xml);

With the above code, we’re ready to test if it works. You can run it from your console:

node rss-script.js

Note that if you stored your file on a different path from the project root, remember to add it to the command. If after running the script you see a new file generated at /public/rss.xml you’re good to go (the file name depends on how you called it with the writeFileSync command).

Now you just need to add the content you want inside the rss.xml feed, blog posts, guides, etc.

In my case, all my content is inside .mdx files in the /data/blog/ directory. This is the content I want for my RSS feed. Now I can add the next few lines to my rss-script. You can see the final result next:

const fs = require('fs');
const path = require('path');
const RSS = require('rss');
const frontMatter = require('front-matter');
 
// NEW LINES
// blog post directory path
const postsDir = path.resolve(__dirname, 'data', 'blog');
const feed = new RSS({
    title: 'Your title here',
    description: 'Your description here',
    feed_url: `https://example.com/rss.xml`,
    site_url: `https://example.com`,
    managingEditor: 'Your name',
    webMaster: 'Your name',
    copyright: `${new Date().getFullYear()} your-name`,
    language: 'en',
    pubDate: new Date().toLocaleString(),
    ttl: '60'
});
 
// NEW LINES
// Read all the files in the blog directory and add them to the RSS feed
fs.readdirSync(postsDir)
    .map(fileName => {
        const fullPath = path.join(postsDir, fileName);
        const file = fs.readFileSync(fullPath, 'utf-8');
        const { attributes } = frontMatter(file);
        return { ...attributes, fileName };
    })
    // title, excerpt, publishedAt, author are properties from my posts metadata
    // you should add yours instead
    .forEach(({ title, excerpt, publishedAt, author, fileName }) => {
        feed.item({
            title,
            excerpt,
            url: `https://example.com/blog/${fileName.replace('.mdx', '')}`,
            author,
            date: publishedAt
        });
    });
 
// Note that before you add each item to the `feed` you can arrange them
// however you like for example, you can sort each file by date using the
// Js sort method or remove what you dont' want. If you have any trouble,
// just store each step in a variable and go one line at the time, at the end
// of the day this is a single file you can run and test as many times as you want.
const xml = feed.xml();
fs.writeFileSync(path.resolve(__dirname, 'public') + '/rss.xml', xml);

Now, run the script again to see if it worked. If you see the additional content inside your rss.xml file, congratulations, you just created your RSS Feed.

One last thing. Currently, this setup runs only manually, if you want to run it automatically every time you create new content, you need to add this postbuild script to your package.json.

{
    "scripts": {
        // ...
        "postbuild": "node rss-script.js"
        // ...
    }
}

This will run the script every time we rebuild the project, keeping the RSS Feed updated.

That’s it…

That’s basically it, now you can generate your RSS feed in an easy way and without having to write any XML.

I hope, this helps!