Building an RSS Feed Reader with TypeScript and Axios

RSS feeds are a classic way to keep up-to-date with new content from various sources. If you’ve ever wanted to create an RSS feed reader using TypeScript, you’ll be happy to know that with modern tools like axios and xml2js, it’s easier than ever. In this post, I’ll guide you step-by-step through creating an RSS feed reader that fetches and parses feeds directly from any source URL.

Thank me by sharing on Twitter 🙏

By the end of this guide, you’ll have a clear understanding of how to set up axios for HTTP requests and use xml2js to convert XML into a manageable JavaScript object.

Why Use Axios and xml2js?

You might be wondering why I chose axios and xml2js for this project. The reason is simple: axios is a robust library for making HTTP requests, and xml2js is a powerful XML parser that converts XML content into JSON. Together, they provide an easy-to-use solution for working with RSS feeds in TypeScript.

Setting Up the Project Dependencies

Before we start coding, you’ll need to install axios and xml2js:

ShellScript
npm install axios xml2js

With these installed, we’re ready to build our TypeScript RSS feed reader.

Fetching and Parsing RSS Feeds with Axios

To fetch and parse RSS feeds, I break the process into two main parts: fetching the data and converting it from XML to a JSON structure. Here’s how to do it step-by-step.

Fetching RSS Feed Data

Fetching data from a URL using axios is straightforward. It handles HTTP requests and returns a Promise that resolves to the response. In our RSS feed reader, we’ll use axios.get() to request data from a feed URL:

TypeScript
import axios from 'axios';

async function fetchRssFeed(url: string): Promise<string> {
  try {
    const response = await axios.get(url, { responseType: 'text' });
    return response.data;
  } catch (error) {
    console.error('Error fetching the RSS feed:', error);
    throw new Error('Failed to fetch RSS feed');
  }
}

In this function, we use axios.get() to fetch data and set responseType to text to ensure we receive a raw string (XML format). If there’s an error during the request, we catch and log it.

Parsing XML Data with xml2js

After fetching the XML, we need to convert it to a format we can work with—like JSON. That’s where xml2js comes in. The parseStringPromise function from xml2js allows us to convert the XML data into a JavaScript object.

Here’s how to parse the XML:

TypeScript
import { parseStringPromise } from 'xml2js';

async function parseRssFeed(xml: string): Promise<any> {
  try {
    const result = await parseStringPromise(xml);
    return result;
  } catch (error) {
    console.error('Error parsing the RSS feed:', error);
    throw new Error('Failed to parse RSS feed');
  }
}

Extracting and Structuring Feed Data

The parsed data from xml2js is often nested and needs a bit of handling to extract the content properly. To make it easier to work with, we should map the data to a structured format with only the properties we need.

TypeScript
interface FeedItem {
  title: string;
  link: string;
  pubDate: string;
  description?: string;
}

async function extractFeedItems(parsedData: any): Promise<FeedItem[]> {
  const items = parsedData.rss.channel[0].item.map((item: any) => ({
    title: item.title[0],
    link: item.link[0],
    pubDate: item.pubDate[0],
    description: item.description[0]
  }));

  return items;
}

In this function, we assume the structure of the parsed XML data is standard for an RSS feed (rss.channel[0].item). We map the data to an array of FeedItem objects, extracting only the title, link, pubDate, and description.

Bringing It All Together

Now that we have functions to fetch, parse, and structure our feed data, let’s combine them into a main function that ties everything together and logs the feed items:

TypeScript
async function fetchAndDisplayRssFeed(url: string): Promise<void> {
  try {
    const xmlData = await fetchRssFeed(url);
    const parsedData = await parseRssFeed(xmlData);
    const feedItems = await extractFeedItems(parsedData);

    console.log('RSS Feed Items:');
    feedItems.forEach((item, index) => {
      console.log(`${index + 1}. ${item.title}`);
      console.log(`   Link: ${item.link}`);
      console.log(`   Published: ${item.pubDate}`);
      console.log(`   Description: ${item.description || 'No description available'}`);
    });
  } catch (error) {
    console.error('Error during RSS feed processing:', error);
  }
}

// Example usage:
const rssUrl = 'https://example.com/rss';
fetchAndDisplayRssFeed(rssUrl);

Conclusion

Building an RSS feed reader using TypeScript, axios, and xml2js is a manageable task once you break it down into clear steps. We first fetched the RSS feed data using axios, parsed it into a JSON format with xml2js, and then structured the content to make it easy to display.

This approach not only helps you understand how to work with external data sources in TypeScript but also highlights the flexibility you have when integrating HTTP requests and XML parsing libraries. With these skills, you can extend your reader to include additional features like feed filtering, user preferences, and more.

RSS feed readers may be old-school, but they remain a powerful way to aggregate and view content across the web efficiently.

Share this:

Leave a Reply