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.
Nexus: A Brief History of Information Networks from the Stone Age to AI
$15.99 (as of December 21, 2024 19:39 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Ultimate Unofficial Encyclopedia for Minecrafters: An A - Z Book of Tips and Tricks the Official Guides Don't Teach You
$11.89 (as of December 21, 2024 19:39 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)SanDisk 256GB Ultra microSDXC UHS-I Memory Card with Adapter - Up to 150MB/s, C10, U1, Full HD, A1, MicroSD Card - SDSQUAC-256G-GN6MA [New Version]
$21.65 (as of December 21, 2024 08:38 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)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
:
npm install axios xml2js
With these installed, we’re ready to build our TypeScript RSS feed reader.
Elon Musk
$16.99 (as of December 21, 2024 19:39 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Nexus: A Brief History of Information Networks from the Stone Age to AI
$22.45 (as of December 21, 2024 19:39 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Super Mario 2025 Wall Calendar
$11.60 (as of December 21, 2024 19:39 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)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:
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:
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.
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:
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.