Skip to content

Instantly share code, notes, and snippets.

@realvjy

realvjy/route.ts Secret

Last active December 14, 2024 18:01
Show Gist options
  • Save realvjy/625a647a1fdf259c59e4388c5089af0d to your computer and use it in GitHub Desktop.
Save realvjy/625a647a1fdf259c59e4388c5089af0d to your computer and use it in GitHub Desktop.
RSS feed using Next.js App Router's route handlers instead of external packages.
// app/feed/route.ts
import { getMetadata } from "@/lib/utils"
import { Blogs } from '@/lib/types'
export async function GET() {
// Get all blog posts using the same method as sitemap
const blogs: Blogs = await getMetadata()
return new Response(
`<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>realvjy's story</title>
<link>https://story.vjy.me</link>
<description>Some thoughts, stories and insights</description>
<language>en</language>
<lastBuildDate>${new Date().toUTCString()}</lastBuildDate>
<atom:link href="https://story.vjy.me/feed" rel="self" type="application/rss+xml"/>
${Object.entries(blogs)
.sort(([, a], [, b]) =>
new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
)
.map(([id, blog]) => {
const url = `https://story.vjy.me/${id}`;
return `
<item>
<title><![CDATA[${blog.title}]]></title>
<link>${url}</link>
<guid isPermaLink="false">${id}</guid>
<description><![CDATA[${blog.description || `Read ${blog.title} on realvjy's story`}]]></description>
<pubDate>${new Date(blog.created_at).toUTCString()}</pubDate>
<author>${blog.author_id}</author>
<category>${blog.category}</category>
</item>`
})
.join('')}
</channel>
</rss>`,
{
headers: {
'Content-Type': 'application/xml; charset=utf-8',
'Cache-Control': 'public, max-age=3600, s-maxage=3600',
},
}
)
}
// import { getMetadata } from "@/lib/utils"
export const getMetadata = async (): Promise<Blogs | null> => {
const res = await fetch(process.env.NEXT_PUBLIC_URL + "/blogs.json");
if (!res.ok) {
return null;
}
return res.json();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment