or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

gatsby-plugin-feed

gatsby-plugin-feed is a Gatsby plugin that automatically generates RSS feeds for your Gatsby site. It provides a flexible configuration system that allows developers to create single or multiple RSS feeds with customizable GraphQL queries, serialization functions, and output locations. The plugin integrates seamlessly with Gatsby's build process and includes server-side rendering support for RSS link tags.

Package Information

  • Package Name: gatsby-plugin-feed
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install gatsby-plugin-feed

Core Imports

This is a Gatsby plugin, so it doesn't export functions directly. Instead, it's configured in your gatsby-config.js:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-feed`,
      options: {
        // Configuration options
      },
    },
  ],
};

Basic Usage

// gatsby-config.js
module.exports = {
  siteMetadata: {
    title: `Your site title`,
    description: `Your site description`,
    siteUrl: `https://your-site-url.com`, // Required for RSS feeds
  },
  plugins: [
    {
      resolve: `gatsby-plugin-feed`,
      options: {
        feeds: [
          {
            serialize: ({ query: { site, allMarkdownRemark } }) => {
              return allMarkdownRemark.nodes.map(node => {
                return Object.assign({}, node.frontmatter, {
                  description: node.excerpt,
                  date: node.frontmatter.date,
                  url: site.siteMetadata.siteUrl + node.fields.slug,
                  guid: site.siteMetadata.siteUrl + node.fields.slug,
                  custom_elements: [{ "content:encoded": node.html }],
                });
              });
            },
            query: `
              {
                allMarkdownRemark(
                  sort: { order: DESC, fields: [frontmatter___date] }
                ) {
                  nodes {
                    excerpt
                    html
                    fields {
                      slug
                    }
                    frontmatter {
                      title
                      date
                    }
                  }
                }
              }
            `,
            output: "/rss.xml",
            title: "Your Site's RSS Feed",
          },
        ],
      },
    },
  ],
};

Architecture

gatsby-plugin-feed is built around Gatsby's plugin architecture and lifecycle hooks:

  • Plugin Configuration: Uses Joi schema validation for configuration options
  • Build Integration: Hooks into Gatsby's onPostBuild lifecycle to generate RSS files
  • SSR Integration: Uses onRenderBody to inject RSS link tags into HTML head
  • GraphQL Integration: Leverages Gatsby's GraphQL layer for data fetching
  • RSS Generation: Built on the robust rss npm package for RSS specification compliance

Capabilities

Plugin Configuration Schema

Validates and processes plugin configuration options using Joi schema validation.

/**
 * Plugin options schema for validating configuration
 * @param {Object} options - Joi validation context
 * @returns {Object} Joi schema object
 */
function pluginOptionsSchema({ Joi }) {
  return Joi.object({
    generator: Joi.string(),
    query: Joi.string(), 
    setup: Joi.func(),
    feeds: Joi.array().items(feedSchema).required(),
  }).unknown(true);
}

/**
 * Individual feed configuration schema
 * @param {Object} options - Joi validation context  
 * @returns {Object} Joi schema for feed configuration
 */
function feedSchema({ Joi }) {
  return Joi.object({
    output: Joi.string().required(),
    query: Joi.string().required(),
    title: Joi.string().required(),
    serialize: Joi.func().required(),
    match: Joi.string(), // Optional regex pattern for page matching
    link: Joi.string(), // Optional custom RSS link override
  }).unknown(true); // Allows additional RSS package options
}

RSS Feed Generation

Main plugin functionality that generates RSS feeds during the Gatsby build process.

/**
 * Gatsby onPostBuild lifecycle hook that generates RSS feeds
 * @param {Object} api - Gatsby API object
 * @param {Function} api.graphql - GraphQL query function
 * @param {Object} api.reporter - Gatsby reporter for logging
 * @param {Object} pluginOptions - Plugin configuration options
 * @returns {Promise<void>} Promise that resolves when feeds are generated
 */
async function onPostBuild({ graphql, reporter }, pluginOptions);

Server-Side Rendering Integration

Injects RSS feed link tags into the HTML head during server-side rendering.

/**
 * Gatsby onRenderBody SSR hook that injects RSS link tags
 * @param {Object} api - Gatsby SSR API object
 * @param {Function} api.setHeadComponents - Function to add components to HTML head
 * @param {string} api.pathname - Current page pathname
 * @param {Object} pluginOptions - Plugin configuration options
 * @returns {void}
 */
function onRenderBody({ setHeadComponents, pathname }, pluginOptions);

Internal Utilities

Helper functions used internally by the plugin.

/**
 * Executes GraphQL queries with error handling
 * @param {Function} handler - GraphQL query handler function
 * @param {string} query - GraphQL query string
 * @returns {Promise<Object>} Promise resolving to query data
 * @throws {Error} Throws error if GraphQL query fails
 */
function runQuery(handler, query);

/**
 * Default plugin configuration options
 * @type {Object}
 */
const defaultOptions = {
  generator: "GatsbyJS",
  query: `
    {
      site {
        siteMetadata {
          title
          description
          siteUrl
          site_url: siteUrl
        }
      }
    }
  `,
  setup: ({ query: { site: { siteMetadata } }, ...rest }) => ({
    ...siteMetadata,
    ...rest,
  }),
  feeds: [
    {
      query: `
        {
          allMarkdownRemark(
            limit: 1000,
            sort: { order: DESC, fields: [frontmatter___date] }
          ) {
            edges {
              node {
                frontmatter {
                  title
                  date
                }
                fields {
                  slug
                }
                excerpt
                html
              }
            }
          }
        }
      `,
      output: "rss.xml",
    },
  ],
};

Configuration Types

Plugin Options

/**
 * Main plugin configuration interface
 * @typedef {Object} PluginOptions
 * @property {string} [generator="GatsbyJS"] - RSS generator tag
 * @property {string} [query] - GraphQL query for site metadata
 * @property {Function} [setup] - RSS feed setup function
 * @property {FeedConfig[]} feeds - Array of feed configurations (required)
 */

/**
 * Individual feed configuration interface
 * @typedef {Object} FeedConfig
 * @property {string} output - Output path for the RSS file (required)
 * @property {string} query - GraphQL query for feed content (required)
 * @property {string} title - RSS feed title (required)
 * @property {Function} serialize - Data serialization function (required)
 * @property {string} [match] - Regex pattern for page matching
 * @property {string} [link] - Custom RSS link override
 * @property {*} [...rssOptions] - Additional options passed to RSS package
 */

/**
 * Feed serialization function signature
 * @typedef {Function} SerializeFunction
 * @param {Object} context - Serialization context
 * @param {Object} context.query - Combined GraphQL query results
 * @returns {Object[]} Array of RSS item objects
 */

/**
 * RSS feed setup function signature
 * @typedef {Function} SetupFunction
 * @param {Object} context - Setup context including query results
 * @returns {Object} RSS feed configuration object
 */

Usage Examples

Multiple Feeds Configuration:

// gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-feed`,
      options: {
        feeds: [
          {
            serialize: ({ query: { site, allMarkdownRemark } }) => {
              return allMarkdownRemark.nodes.map(node => ({
                title: node.frontmatter.title,
                description: node.excerpt,
                date: node.frontmatter.date,
                url: site.siteMetadata.siteUrl + node.fields.slug,
                guid: site.siteMetadata.siteUrl + node.fields.slug,
              }));
            },
            query: `
              {
                allMarkdownRemark(
                  filter: { frontmatter: { category: { eq: "blog" } } }
                  sort: { order: DESC, fields: [frontmatter___date] }
                ) {
                  nodes {
                    excerpt
                    fields { slug }
                    frontmatter {
                      title
                      date
                    }
                  }
                }
              }
            `,
            output: "/blog/rss.xml",
            title: "Blog Posts RSS Feed",
            match: "^/blog/", // Only include RSS link on blog pages
          },
          {
            serialize: ({ query: { site, allMarkdownRemark } }) => {
              return allMarkdownRemark.nodes.map(node => ({
                title: node.frontmatter.title,
                description: node.excerpt,
                date: node.frontmatter.date,
                url: site.siteMetadata.siteUrl + node.fields.slug,
              }));
            },
            query: `
              {
                allMarkdownRemark(
                  filter: { frontmatter: { category: { eq: "news" } } }
                  sort: { order: DESC, fields: [frontmatter___date] }
                ) {
                  nodes {
                    excerpt
                    fields { slug }
                    frontmatter {
                      title
                      date
                    }
                  }
                }
              }
            `,
            output: "/news/rss.xml",
            title: "News RSS Feed",
            link: "https://feeds.feedburner.com/my-news-feed", // Custom RSS URL
          },
        ],
      },
    },
  ],
};

Advanced RSS Configuration with Custom Namespaces:

// gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-feed`,
      options: {
        feeds: [
          {
            serialize: ({ query: { site, allMarkdownRemark } }) => {
              return allMarkdownRemark.nodes.map(node => ({
                title: node.frontmatter.title,
                description: node.excerpt,
                url: site.siteMetadata.siteUrl + node.fields.slug,
                guid: site.siteMetadata.siteUrl + node.fields.slug,
                custom_elements: [
                  { "content:encoded": node.html },
                  { "media:thumbnail": { _attr: { url: node.frontmatter.image } } },
                ],
              }));
            },
            query: `
              {
                allMarkdownRemark(
                  sort: { order: DESC, fields: [frontmatter___date] }
                ) {
                  nodes {
                    excerpt
                    html
                    fields { slug }
                    frontmatter {
                      title
                      date
                      image
                    }
                  }
                }
              }
            `,
            output: "/rss.xml",
            title: "My Site RSS Feed",
            // Custom RSS namespaces
            custom_namespaces: {
              media: 'http://search.yahoo.com/mrss/',
              content: 'http://purl.org/rss/1.0/modules/content/',
            },
            language: "en-US",
          },
        ],
      },
    },
  ],
};

Error Handling

The plugin handles several error scenarios:

  • GraphQL Query Errors: Throws descriptive errors if GraphQL queries fail
  • Missing Serialize Function: Reports warning and skips feed generation if serialize function is missing or invalid
  • Invalid Configuration: Joi schema validation catches configuration errors during Gatsby build
  • File System Errors: Handles directory creation and file writing errors during RSS generation

Common Error Scenarios:

// Missing required serialize function
{
  resolve: `gatsby-plugin-feed`,
  options: {
    feeds: [
      {
        output: "/rss.xml",
        query: "{ site { siteMetadata { title } } }",
        title: "My Feed",
        // Missing serialize function - will trigger warning
      },
    ],
  },
}

// Invalid GraphQL query
{
  resolve: `gatsby-plugin-feed`,
  options: {
    feeds: [
      {
        output: "/rss.xml",
        query: "{ invalidField }", // Invalid query - will cause build error
        title: "My Feed",
        serialize: ({ query }) => [],
      },
    ],
  },
}