Back to Blog
Lesson 43 of the Next.js: Build Full-Stack Apps with the App Router course
Next.jsAugust 30, 20263 min read

Adding RSS Feed: Generating Dynamic XML in Next.js

Learn how to build an RSS feed for your Next.js blog. Create an API route, generate dynamic XML, and serve your content to feed readers automatically.

Next.jsRSSAPIXMLWeb DevelopmentContent

Previously in this course, we explored mastering static site generation (SSG) in next.js to optimize our blog's performance. In this lesson, we are adding an RSS feed to our project, allowing users to subscribe to our content updates through modern feed readers.

RSS (Really Simple Syndication) is a standardized XML format that allows users to consume your content without visiting your site. By generating a dynamic feed, you ensure your readers never miss a post.

Understanding the RSS Feed Concept

An RSS feed is essentially an XML file that lists your blog posts with metadata like the title, link, publication date, and description. While your users read your site as HTML, feed readers require a specific XML schema (RSS 2.0 or Atom).

In the Next.js App Router, we don't need a static file. Instead, we use a Route Handler to generate this XML on the fly, fetching the latest posts from our database. This ensures that every time someone hits /rss.xml, they get the most recent data.

Creating the RSS API Route

In the App Router, we use route.js files to handle requests that aren't meant to return UI components. We will place this in app/rss.xml/route.ts to map the URL directly to our desired output.

First, ensure you have a utility to fetch your posts (we covered this in fetching data from the database in next.js server components).

TYPESCRIPT
// app/rss.xml/route.ts
import { prisma } from "@/lib/prisma";

export async function GET() {
  const posts = await prisma.post.findMany({
    orderBy: { createdAt: CE9178">'desc' },
    take: 20,
  });

  const xml = CE9178">`<?xml version="1.0" encoding="UTF-8"?>
    <rss version="2.0">
      <channel>
        <title>My Awesome Blog</title>
        <link>https://yourdomain.com</link>
        <description>Latest posts from my blog</description>
        ${posts.map(post => `
          <item>
            <title>${post.title}</title>
            <link>https://yourdomain.com/blog/${post.slug}</link>
            <pubDate>${new Date(post.createdAt).toUTCString()}</pubDate>
          </item>
        CE9178">`).join('')}
      </channel>
    </rss>`;

  return new Response(xml, {
    headers: {
      CE9178">'Content-Type': CE9178">'application/xml',
    },
  });
}

Serving RSS Content

The code above performs three critical steps:

  1. Fetching: It queries the database for the latest posts.
  2. Transforming: It injects the data into a template string formatted as valid XML.
  3. Serving: It returns a Response object with the Content-Type header set to application/xml.

Without this header, the browser might try to render your XML as plain text or HTML, which would break the feed reader's ability to parse it.

Hands-on Exercise

  1. Create the app/rss.xml/route.ts file as shown above.
  2. Update the link and title tags to reflect your actual blog's information.
  3. Start your development server and navigate to http://localhost:3000/rss.xml.
  4. Verify that you see the XML output in your browser.

Common Pitfalls

  • XML Escaping: If your post titles or descriptions contain special characters like & or <, your XML will be invalid. Always sanitize or escape these characters before injecting them into the string.
  • Missing Headers: Forgetting the application/xml header is the most frequent cause of "broken" feeds.
  • Caching: By default, Next.js might cache this response. If you want the feed to update instantly, you may need to use the revalidate route segment config: export const revalidate = 3600; (to revalidate every hour).

FAQ

Q: Should I use a library for this? A: For simple feeds, a template string is sufficient. If you need complex features (like enclosure tags for podcasts), look into the rss npm package.

Q: Does this affect my SEO? A: Yes, providing an RSS feed makes it easier for crawlers and aggregators to index your content, which is a net positive for your visibility.

Q: Can I use this for non-blog content? A: Absolutely. Any data that changes over time (like a changelog or product updates) is a great candidate for an RSS feed.

Recap

We've successfully added an RSS feed by creating a dedicated API route that serves dynamic XML. We learned how to fetch our database posts, map them to the RSS 2.0 schema, and set the correct content headers. This simple addition significantly improves the reach of our content.

Up next: Integrating Third-Party Scripts

Similar Posts