go to index

nextjs13增加rss feed订阅

read time 1 min read
Nextjs rss 订阅

安装依赖

安装 rss 包及其类型定义:

bash
npm install rss
npm install -D @types/rss

创建 RSS 文件

在项目中创建文件 app/rss.xml/route.ts,并添加以下代码:

typescript
import api from "../axios/api";
import Rss from "rss";
import { getPosts } from "../data/post.data";

const SITE_URL = "https://www.jason-z.com";

// 截取 HTML 内容并去除标签
function truncateHTML(htmlString, maxLength) {
    const plainText = htmlString.replace(/<[^>]*>/g, '');
    return plainText.substring(0, maxLength);
}

export async function GET() {
    const posts = await getPosts();

    const feed = new Rss({
        title: "张晓刚的博客",
        description: "学习,记录,思考,分享",
        feed_url: `${SITE_URL}/rss.xml`,
        site_url: SITE_URL,
        language: "en",
    });

    posts.forEach((post) => {
        feed.item({
            title: post.attributes.title,
            description: truncateHTML(post.attributes.content, 100),
            url: `${SITE_URL}/posts/${post.attributes.slug}`,
            guid: `${SITE_URL}/posts/${post.id}`,
            date: post.publishedAt,
        });
    });

    return new Response(feed.xml(), {
        headers: {
            "Content-Type": "application/xml",
        },
    });
}

访问 RSS

访问 https://www.jason-z.com/rss.xml 即可查看 RSS 内容。