next-sitemap

repository·master·Indexed 25 days ago

https://github.com/iamvishnusankar/next-sitemap

A tool for Next.js applications to automate the generation of sitemaps and robots.txt files. It supports index sitemaps, splitting large sitemaps into multiple files, server-side sitemap generation for App and Pages routers, and custom configuration via next-sitemap.config.js. Features include multi-language support, custom transformers for sitemap entries, and integration with Google News, Image, and Video tags.

Tokens
12.7K
Snippets
42
Records
68
Agent score
84%

What's inside next-sitemap

  1. Create next-sitemap.config.js

    master

    Create a next-sitemap.config.js file in your project root to configure your sitemap settings. next-sitemap automatically loads environment variables from your .env files. Use the IConfig type for better IDE support.

    /** @type {import('next-sitemap').IConfig} */
    module.exports = {
      siteUrl: process.env.SITE_URL || 'https://example.com',
      generateRobotsTxt: true, // (optional)
      // ...other options
    }
  2. Use the transform function for custom sitemap transformations

    master

    The transform function allows you to add, remove, or exclude path or properties from the generated sitemap. This function runs for each relative path in the sitemap.

    • To exclude a path: Return null from the transformation function. This will prevent that specific relative path from being included in the generated sitemap.
    • To customize properties: Return an object containing the desired XML fields. Returning a partial object (e.g., only loc and changefreq) will result in an XML entry containing only those specific fields.
    • The loc property: When returning an object, the loc value is exported as http(s)://<config.siteUrl>/<path>.
    /** @type {import('next-sitemap').IConfig} */
    module.exports = {
      transform: async (config, path) => {
        // custom function to ignore the path
        if (customIgnoreFunction(path)) {
          return null
        }
    
        // only create changefreq along with path
        // returning partial properties will result in generation of XML field with only returned values.
        if (customLimitedField(path)) {
          // This returns `path` & `changefreq`. Hence it will result in the generation of XML field with `path`
          // and `changefreq` properties only.
          return {
            loc: path, // => this will be exported as http(s)://<config.siteUrl>/<path>
            changefreq: 'weekly',
          }
        }
    
        // Use default transformation for all other cases
        return {
          loc: path, // => this will be exported as http(s)://<config.siteUrl>/<path>
          changefreq: config.changefreq,
          priority: config.priority,
          lastmod: config.autoLastmod ? new Date().toISOString() : undefined,
          alternateRefs: config.alternateRefs ?? [],
        }
      },
    }
  3. Generate a server-side sitemap with the App Router

    master

    To generate a dynamic sitemap using the Next.js App Router, create a route handler at app/server-sitemap.xml/route.ts. Use the getServerSideSitemap function to return the sitemap content based on an array of URL objects. This is useful for sourcing URLs from a CMS or external API at request time.

    // app/server-sitemap.xml/route.ts
    import { getServerSideSitemap } from 'next-sitemap'
    
    export async function GET(request: Request) {
      // Method to source urls from cms
      // const urls = await fetch('https//example.com/api')
    
      return getServerSideSitemap([
        {
          loc: 'https://example.com',
          lastmod: new Date().toISOString(),
          // changefreq
          // priority
        },
        {
          loc: 'https://example.com/dynamic-path-2',
          lastmod: new Date().toISOString(),
          // changefreq
          // priority
        },
      ])
    }
  4. Generate index-sitemaps on the server side with the /app directory

    master

    Use the getServerSideSitemapIndex API to generate a dynamic sitemap index within the Next.js App Router. Create a route handler at app/server-sitemap-index.xml/route.ts that returns the result of getServerSideSitemapIndex with an array of sitemap URLs.

    // app/server-sitemap-index.xml/route.ts
    import { getServerSideSitemapIndex } from 'next-sitemap'
    
    export async function GET(request: Request) {
      // Method to source urls from cms
      // const urls = await fetch('https//example.com/api')
    
      return getServerSideSitemapIndex([
        'https://example.com/path-1.xml',
        'https://example.com/path-2.xml',
      ])
    }
  5. Include dynamic index-sitemaps in robots.txt

    master

    When serving a dynamic index-sitemap via Next.js, you must prevent it from being included in the static sitemap list while explicitly adding it to the robots.txt file.

    1. Add the dynamic path to the exclude array in next-sitemap.config.js.
    2. Add the full URL of the dynamic sitemap to robotsTxtOptions.additionalSitemaps.
    // next-sitemap.config.js
    
    /** @type {import('next-sitemap').IConfig} */
    module.exports = {
      siteUrl: 'https://example.com',
      generateRobotsTxt: true,
      exclude: ['/server-sitemap-index.xml'], // <= exclude here
      robotsTxtOptions: {
        additionalSitemaps: [
          'https://example.com/server-sitemap-index.xml', // <==== Add here
        ],
      },
    }
  6. Generate a server-side sitemap with the Pages Router (Legacy)

    master

    For legacy Next.js projects using the Pages Router, create a file at pages/server-sitemap.xml/index.tsx. Use getServerSideSitemapLegacy within getServerSideProps. The function requires the Next.js context (ctx) and an array of URL objects. You must also provide a default export to prevent Next.js errors.

    // pages/server-sitemap.xml/index.tsx
    import { getServerSideSitemapLegacy } from 'next-sitemap'
    import { GetServerSideProps } from 'next'
    
    export const getServerSideProps: GetServerSideProps = async (ctx) => {
      // Method to source urls from cms
      // const urls = await fetch('https//example.com/api')
    
      const fields = [
        {
          loc: 'https://example.com', // Absolute url
          lastmod: new Date().toISOString(),
          // changefreq
          // priority
        },
        {
          loc: 'https://example.com/dynamic-path-2', // Absolute url
          lastmod: new Date().toISOString(),
          // changefreq
          // priority
        },
      ]
    
      return getServerSideSitemapLegacy(ctx, fields)
    }
    
    // Default export to prevent next.js errors
    export default function Sitemap() {}