Automating an RSS feed with Nuxt, Cosmic and the @nuxtjs/feed module

Community Articles
Community Articles Automating an RSS feed with Nuxt, Cosmic and the @nuxtjs/feed module

For many months I'd been pondering the idea of setting up automated RSS population via the Nuxt Feed module but couldn't find many good tutorials or guides on how to work with external CMS sources.

The main use case shown for the module was to use the Nuxt Content module alongside the Feed module to use markdown and build out your feed that way via Git commits. Whilst this is great, it didn't align with my use case of utilising my Cosmic CMS integration and my Drafts›››Cosmic workflow.

After a lot of blood, sweat, tears, and throwing my hands up in the air I eventually figured out how to handle the process with Axios and the Cosmic REST API. Your mileage may vary, but this remains a concise and functioning way to handle things, if you've got recommendations or improvements, share them in the comments below.

Setting things up

First thing's first, you'll need to download the Feed module from npm.

yarn add @nuxtjs/feed # or npm install @nuxtjs/feed

Then, you'll need to insert the module into your nuxt.config.js and include the feed configuration.

export default {
  modules: [
    '@nuxtjs/feed'
      ],
      feed: [
    // Your feeds here
  ]
}

Fetching our data

We want to ensure the data we fetch is always from the API directly and not locally sourced, that way it's always accurate to what is rendered on your site. To do that, we need Axios so the next step is to install Axios and import it to your nuxt.config.js

yarn add axios # or npm install axios

Then at the top of your nuxt.config.js file add import axios from "axios";

Once this is ready, we can now safely use axios get() but we'll come to that shortly.

Putting the pieces together

Firstly we'll want to actually create our feed and then define the core feed constants, these are the details about your blog's name, your site name, and description.

path: "/rss.xml",
    async create(feed) {
        feed.options = {
          title: "your-blog-name-here",
          link: "https://www.your-website.com/rss",
          description:
            "Your awesome blog",
      };

Once we're done with that we'll want to initialise an empty array so we can have a place to store our fetched blog post object data. We can do that by including the following below our feed creation.

let all_blogs = [];

Fetching our blogs from Cosmic

Now, we're ready to fetch our actual feed data from Cosmic with the REST API v2. Below your empty array, you'll need to include the following (make sure you grab this yourself by heading to your blog object, clicking the Developer tools button, and copying your REST API link).

await axios
           .get(`https://api.cosmicjs.com/v2/buckets/{your-bucket-name}/objects?pretty=true&query=%7B%22type%22%3A%22{your-object-type}%22%7D&read_key={your-read-key}&limit={your-total-limit}&props=slug,title,content,metadata,modified_at`)
          .then((res) => {
            res.data.objects.forEach((blog) => {
              all_blogs.push(blog);
         });
});

For the purpose of this tutorial, I've left my props in as they're used later.

As you can see in the above code, we asynchronously await our feed data and then take that JSON response and parse it by taking the data and targeting our objects array. We then define a blog argument in our forEach method which allows us to use the handy .push() array method to fill our empty array with all our individual posts.

Looping through the posts to generate your feed

Now finally we need to loop through our newly fetched array of objects and construct the feed. To do this, we use another .forEach() method.

The following assumes that your individual items are called blogs, but really you can use whatever nomenclature you prefer, just ensure that whatever argument is passed into your .forEach() method is what you carry through. Here, I've chosen Blog because it matches my Cosmic bucket.

all_blogs.forEach((blog) => {
     const url = `https://your-website.com/${blog.slug}`;
          feed.addItem({
            title: blog.title,
            id: url,
            link: url,
            description: blog.metadata.snippet,
            image: blog.metadata.hero.imgix_url,
            content: blog.content,
            published: new Date(blog.modified_at),
            author: [
         {
          name: "Your Name", // optional
          email: "Your email address", // optional
        },
      ],
     });
   });
},

So here you can see that we take our array all_blogs and loop through it to create an individual feed item per-blog.

For each item we include:

  • Its title
  • A unique id (where we use the provided by Cosmic)
  • The actual link to the post as hosted on our site
  • A brief description (I have a snippet object within my Blog object, I'd recommend doing the same so it can be unique. Alternatively, you could use a substring method to trim the start of your content object too)
  • An image link to be used by the feed on popular tools like Feedly (optional)
  • The full article content (this is optional if you want to link straight through to your site from a snippet, remove this line)
  • The published date (here I pull the modified_at date from Cosmic as I believe in the idea of 'incrementally correct' websites versus static content that is never improved, see a post by Brian Lovin on this)
  • Finally we include the author details

The last piece of the puzzle

Finally, we need to tell our module the expected cacheTime, i.e. how long we want the feed to be cached for, and finally what type of feed we want to create.

cacheTime: 1000 * 60 * 15,
  type: "rss2",
},

And that's it

Once we've done that, all that's left is to run yarn generate # or npm run generate to watch our feed magically come to life. If all the things set out above are correct you'll see a new rss.xml file in your dist directory. Go ahead and double-check it to see if your feed items and information match what's expected.

Now when you publish your site again and visit https://www.your-website.com/rss you should see that it prompts you to open an RSS reader (if you have one installed). Awesome!

Hopefully, this has been helpful. I've tried for months to get this right and most methods I tried failed, so here we go, one that works.

You may also like


To demonstrate how easy it is to get started with Cosmic, we'll utilize the Cosmic CLI to quickstart a Vue.js Music App. This Music website was built using Vue, Nuxt and Cosmic. Users can upload and play tracks, upload and manage album art plus leave comments.
Cosmic makes it easy to manage content for your Bootstrap applications. In this blog we'll quickstart a Bootstrap Landing Page using the Cosmic CLI. This single page website landing page is built using Node.js and a minimal theme from Start Bootstrap.
In this article I’m going demonstrate how to add new form submissions to Hubspot when you Publish Objects in your Cosmic Bucket.
Thanks to everyone in Dallas who came out to the Vuetiful Holiday Meetup at Simple Media, featuring Vuetify, Netlify and Cosmic. 🎉
Hi, In this tutorial, we are going to create an application that filters twitter tweets by selecting a specific location on the map. We are going to use React and Cosmic. We will be using Cosmic npm package for saving and sorting the most popular searches in our application. Let's get started.
Todo List app built using Svelte that utilizes the power of Cosmic.

Get Started with Cosmic

Build personal projects for free. Add your team at unbeatable prices.
Start Building Talk to Sales