AstroにRSSをつける方法

2023/07/19

pages/rss.xml.ts

import rss from '@astrojs/rss';
import { getCollection } from "astro:content";

export async function get(context) {
    const allPosts = (await getCollection("blog"));
    const sortedPosts = allPosts.sort((a, b) => 
        Math.floor(new Date(b.data.pubDate).getTime() / 1000) -
        Math.floor(new Date(a.data.pubDate).getTime() / 1000)
    ).slice(0,5);

    return rss({
        title: 'Na2x Blog',
        description: 'Na2x Blog',
        site: 'https://na2x.com/',
        items: sortedPosts.map((post) => ({
            link: SITE.url + "blog/slug/" + post.slug + '/s',
            title: post.data.title,
            pubDate: post.data.pubDate,
            description: post.data.description,
        })),
    });
}

pages/index.astro

	<head>
		<link rel='alternate' type='application/rss+xml' href='https://na2x.com/rss.xml' />
	</head>

最後にこのサイトでエラーチェック https://validator.w3.org/feed/

(参考) https://docs.astro.build/ja/guides/rss/