ข้ามไปเนื้อหาหลัก

Category: guide

สร้าง RSS Feed กับ Astro — @astrojs/rss

วิธีตั้งค่า RSS feed สำหรับ Astro static site ด้วย @astrojs/rss รองรับ Content Collections และ custom channel metadata

· อ่านประมาณ 1 นาที

สารบัญ

ติดตั้ง

npm install @astrojs/rss

สร้าง /rss.xml

// src/pages/rss.xml.ts
import rss from '@astrojs/rss';
import { getCollection } from 'astro:content';
import type { APIContext } from 'astro';

export async function GET(context: APIContext) {
  const posts = await getCollection('notes');

  return rss({
    title: 'Panupong WS — Notes',
    description: 'TIL notes เรื่อง web development',
    site: context.site!,
    items: posts
      .sort((a, b) => b.data.date.getTime() - a.data.date.getTime())
      .map((post) => ({
        title: post.data.title,
        pubDate: post.data.date,
        description: post.body?.slice(0, 200),
        link: `/notes/${post.id}/`,
      })),
    customData: `<language>th</language>`,
  });
}

ตั้งค่าใน astro.config

// astro.config.mjs
export default defineConfig({
  site: 'https://panupongws.com',
  // site ต้องมีเพื่อให้ context.site ถูกต้อง
});

รวมหลาย collections

const [notes, resources] = await Promise.all([
  getCollection('notes'),
  getCollection('resources'),
]);

const allItems = [...notes, ...resources]
  .sort((a, b) => b.data.date.getTime() - a.data.date.getTime())
  .slice(0, 20);  // latest 20

เพิ่ม autodiscovery ใน HTML

---
// src/layouts/Layout.astro
---
<link rel="alternate" type="application/rss+xml"
  title="Panupong WS RSS Feed"
  href="/rss.xml" />

สำหรับ @astrojs/rss v4+ ใช้ sanitizeHtml และ markdown() render post body เป็น HTML ใน feed ได้