aljoseph.co

Generating RSS feed

Apr 29, 2021☕️ 2 min read

rss feed

TL;DR

Just click this link to my commit on implementing rss feed on my site.

What is RSS feed?

RSS stands for Really Simple Syndication. It is an XML file that contains all the information about you website. Mostly of the readers like to use RSS readers like Feeder to read a blog posts.

Create a function to generate RSS feed.

To generate an rss feed i used the this npm package just run npm i rss to install it.

Create a utility function in my case i named it /utils/rss.js. Since I am using .mdx for my blog I need to extract the data using nodejs built in libraries.

const { promises: fs } = require('fs');
const { join } = require('path');
const RSS = require('rss');
const matter = require('gray-matter');

const postDirectory = join(process.cwd(), '_posts');

async function getPostSlugs() {
    return await fs.readdir(postDirectory);
}

async function generate() {
    const feed = new RSS({
        title: 'Al Joseph Condino',
        site_url: 'https://aljoseph.co',
        feed_url: 'https://aljoseph.co/feed.xml'
    });

    const slugs = await getPostSlugs();

    await Promise.all(
        slugs.map(async (slug) => {
            const fullPath = join(postDirectory, slug);
            const fileContents = await fs.readFile(fullPath, 'utf8');

            const { data, content } = matter(fileContents);

            feed.item({
                title: data.title,
                url: 'https://aljoseph.co/posts/' + slug.replace(/\.mdx?/, ''),
                date: data.date,
                description: data.excerpt
            });
        })
    );

    return await fs.writeFile('./public/feed.xml', feed.xml({ indent: true }));
}

generate();

This function generates an rss feed and save it to my public assets ./public/feed.xml. Make sure to only run the generator on the server-side. So on your next.config.js add a custom webpack configuration.

const withMDX = require('@next/mdx')({
    extension: /\.mdx?$/
});

module.exports = withMDX({
    pageExtensions: ['js', 'jsx', 'md', 'mdx'],
    images: {
        domains: ['pbs.twimg.com', 'images.unsplash.com']
    },
webpack: (config, { isServer }) => {
if (isServer) {
require('./utils/rss');
}
return config;
}
});

The isServer property is for server-side compilation. That means we will only trigger the rss generator on the server-side.

Lastly make sure to add feed.xml on your .gitignore.