aljoseph.co

Adding RSS feed to your Next.js app

Apr 29, 2021☕️ 3 min read

Having RSS feed helps us to stay up-to-date with the latest content from our favorite websites. In this blog post, I will quickly show you how to create your own.

What is RSS feed?

RSS stands for Really Simple Syndication. It is an XML file that contains all the information about your website. Mostly of the readers like to use RSS readers like Feeder to easily stay informed about your latest posts.

Installing the necessary npm package

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

npm i rss

Create a function to generate RSS feed

I have all my posts stored locally on _posts directory and manage it using contentlayer.

Extracting data from .mdx files

Since I use the .mdx file format on my posts, I must use the built-in Nodejs utilities to extract the data.

const { promises: fs } = require("fs");
const { join } = require("path");

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

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

In this snippet, where creating an asynchronous function fetch all our post slugs.

Generating the RSS feed

Now, we just have to map through post slugs and read those file contents.

const matter = require("gray-matter");

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();

We parse those front matters from our file contents to get each of those metadata on our posts. Then, we save the generated feed on our public assets ./public/feed.xml.

Here's the final code snippet.

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();

Configuring Webpack

Make sure to only run the generator on the server-side. So on your next.config.js add a custom webpack configuration.

const { withContentlayer } = require('next-contentlayer')

module.exports = withContentlayer({
	pageExtensions: ['tsx', 'md', 'mdx'],
webpack: (config, { isServer }) => {
if (isServer) {
require('./scripts/rss');
}
return config;
},
experimental: { appDir: true } })

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.

Conclusion

By following this simple tutorial, we have walk through to the importance of having RSS feed and step by step process of creating it on your Nextjs app.

You have now enabled your readers to keep up with your latest posts. Happy blogging!