RSS is a standard format for publishing frequently updated content, such as blog posts, news articles, and podcast episodes. It allows users to subscribe to a feed, which then delivers new content automatically, often in the form of brief summaries and links to full articles and bla, bla, bla. Simply put RSS is an XML doc which describes how to retrieve your content to a 3rd parties.
I use Remix
for my blog and I want to allow the readers to subscribe to the content via RSS. To be honest, I've never worked with it before and at first it sounded to me like some wobbly-bubbly thing. Though after reading a W3School's article it became extremely simple.
Although Remix
is considered a React
framework, its capabilities are way more. Resource routes allow creating endpoints and handling of custom routes. For my feed I decided to go with /blog/rss.xml
route. The only thing I needed in that file is a loader which retrieves blog's data and formats it to a valid RSS XML. I ended up with the following code.
blog.[rss.xml].tsx
import { api } from 'api'
import { toRssFeed } from 'utils/xml'
export const loader = async () => {
const blogInfo = await api.pages.getByName('blog')
const posts = await api.blog.getAll()
return new Response(toRssFeed(blogInfo, posts), {
status: 200,
headers: {
'Content-Type': 'application/rss+xml',
},
})
}
And the transformation was as simple as this.
const toRssFeed = (blogInfo: Page, posts: BlogPost[]) => {
const postItems = posts
.map((post) => {
const link = env.BASE_URL + '/blog/' + post.slug
const date =
post.datePublished && new Date(post.datePublished).toUTCString()
return `<item>
<title>${post.name}</title>
<link>${link}</link>
${date ? `<pubDate>${date}</pubDate>` : ''}
<guid>${link}</guid>
</item>`
})
.join('')
const rssDescription = `
<title>${blogInfo.title}</title>
<description>${blogInfo.description}</description>
<link>${env.BASE_URL + '/blog/rss.xml'}</link>
`
return `<?xml version="1.0" encoding="UTF-8" ?><rss version="2.0"><channel>${rssDescription}${postItems}</channel></rss>`
}
Top comments (1)
You can also read it on my blog.