Next.js で RSS フィードを動的に生成
投稿日: 2025-06-07
カテゴリ: tech

app/rss.xml/route.ts を作成
RSS リーダーで全文読めるようにしたいので、HTML タグ付きで全文表示するように変更した。
import { client, Blog } from "@/lib/microcms";
import { type NextRequest } from "next/server";
export async function GET(_req: NextRequest) {
const baseUrl = "https://yosuke.ai";
const siteTitle = "Draft Note";
const siteDescription = "技術メモや日々の記録";
// microCMS からブログ一覧を取得(最新20件)
const { contents } = await client.getList<Blog>({
endpoint: "blogs",
queries: {
limit: 20,
orders: "-publishedAt",
},
});
// 各記事のRSSアイテムを作成
const rssItems = contents.map((post) => {
// 記事全文をHTMLタグ付きで使用
const description = post.content || "";
return `
<item>
<title><![CDATA[${post.title}]]></title>
<link>${baseUrl}/blog/${post.id}</link>
<description><![CDATA[${description}]]></description>
<pubDate>${new Date(post.publishedAt).toUTCString()}</pubDate>
<guid isPermaLink="true">${baseUrl}/blog/${post.id}</guid>
<dc:creator><![CDATA[yosuke]]></dc:creator>
${post.category ? `<category><![CDATA[${post.category.name}]]></category>` : ""}
</item>`;
});
// RSS 2.0 フィード生成
const rss = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
<title><![CDATA[${siteTitle}]]></title>
<link>${baseUrl}</link>
<description><![CDATA[${siteDescription}]]></description>
<language>ja</language>
<lastBuildDate>${new Date().toUTCString()}</lastBuildDate>
<pubDate>${contents.length > 0 ? new Date(contents[0].publishedAt).toUTCString() : new Date().toUTCString()}</pubDate>
<ttl>60</ttl>
${rssItems.join("")}
</channel>
</rss>`;
return new Response(rss, {
headers: {
"Content-Type": "application/xml",
},
});
}
動作確認
- ローカルで http://localhost:3000/rss.xml にちゃんと出てるか確認
- 問題なかったので更新
RSS Feed へのリンクを head に追加
app/layout.tsx に以下を追加。
<link
rel="alternate"
type="application/rss+xml"
title="RSS feed for Draft Note"
href="/rss.xml"
/>
動作確認
URL を入れたら読み込むフィードがちゃんと表示され、ちゃんとリーダーで見れた。


