Created
November 29, 2019 15:21
-
-
Save fredrikbergqvist/36704828353ebf5379a5c08c7583fe2d to your computer and use it in GitHub Desktop.
How to create an RSS feed for next.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import { NextPageContext } from "next"; | |
const blogPostsRssXml = (blogPosts: IBlogPost[]) => { | |
let latestPostDate: string = ""; | |
let rssItemsXml = ""; | |
blogPosts.forEach(post => { | |
const postDate = Date.parse(post.createdAt); | |
if (!latestPostDate || postDate > Date.parse(latestPostDate)) { | |
latestPostDate = post.createdAt; | |
} | |
rssItemsXml += ` | |
<item> | |
<title>${post.title}</title> | |
<link> | |
${post.href} | |
</link> | |
<pubDate>${post.createdAt}</pubDate> | |
<description> | |
<![CDATA[${post.text}]]> | |
</description> | |
</item>`; | |
}); | |
return { | |
rssItemsXml, | |
latestPostDate | |
}; | |
}; | |
const getRssXml = (blogPosts: IBlogPost[]) => { | |
const { rssItemsXml, latestPostDate } = blogPostsRssXml(blogPosts); | |
return `<?xml version="1.0" ?> | |
<rss version="2.0"> | |
<channel> | |
<title>Blog by Fredrik Bergqvist</title> | |
<link>https://www.bergqvist.it</link> | |
<description>${shortSiteDescription}</description> | |
<language>en</language> | |
<lastBuildDate>${latestPostDate}</lastBuildDate> | |
${rssItemsXml} | |
</channel> | |
</rss>`; | |
}; | |
export default class Rss extends React.Component { | |
static async getInitialProps({ res }: NextPageContext) { | |
if (!res) { | |
return; | |
} | |
const blogPosts = getRssBlogPosts(); | |
res.setHeader("Content-Type", "text/xml"); | |
res.write(getRssXml(blogPosts)); | |
res.end(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment