Project Icon

next-sitemap

自动化生成和管理Next.js网站站点地图的高效工具

next-sitemap是一款用于Next.js项目的自动化工具,可生成和管理站点地图及robots.txt文件。该工具支持自定义配置、动态生成、多语言和服务器端生成等功能,有助于优化网站SEO。通过灵活的API,开发者可根据需求进行定制,提高搜索引擎对网站内容的爬取和索引效率。

BANNER

Table of contents

Getting started

Installation

yarn add next-sitemap

Create config file

next-sitemap requires a basic config file (next-sitemap.config.js) under your project root

next-sitemap will load environment variables from .env files by default.

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

Building sitemaps

Add next-sitemap as your postbuild script

{
  "build": "next build",
  "postbuild": "next-sitemap"
}

Custom config file

You can also use a custom config file instead of next-sitemap.config.js. Just pass --config <your-config-file>.js to build command (Example: custom-config-file)

{
  "build": "next build",
  "postbuild": "next-sitemap --config awesome.config.js"
}

Building sitemaps with pnpm

When using pnpm you need to create a .npmrc file in the root of your project if you want to use a postbuild step:

//.npmrc
enable-pre-post-scripts=true

Index sitemaps (Optional)

📣 From next-sitemap v2.x onwards, sitemap.xml will be Index Sitemap. It will contain urls of all other generated sitemap endpoints.

Index sitemap generation can be turned off by setting generateIndexSitemap: false in next-sitemap config file. (This is useful for small/hobby sites which does not require an index sitemap) (Example: no-index-sitemaps)

Splitting large sitemap into multiple files

Define the sitemapSize property in next-sitemap.config.js to split large sitemap into multiple files.

/** @type {import('next-sitemap').IConfig} */
module.exports = {
  siteUrl: 'https://example.com',
  generateRobotsTxt: true,
  sitemapSize: 7000,
}

Above is the minimal configuration to split a large sitemap. When the number of URLs in a sitemap is more than 7000, next-sitemap will create sitemap (e.g. sitemap-0.xml, sitemap-1.xml) and index (e.g. sitemap.xml) files.

Configuration Options

propertydescriptiontype
siteUrlBase url of your websitestring
output (optional)Next.js output modes. Check documentation.standalone, export
changefreq (optional)Change frequency. Default dailystring
priority (optional)Priority. Default 0.7number
sitemapBaseFileName (optional)The name of the generated sitemap file before the file extension. Default "sitemap"string
alternateRefs (optional)Denote multi-language support by unique URL. Default []AlternateRef[]
sitemapSize(optional)Split large sitemap into multiple files by specifying sitemap size. Default 5000number
autoLastmod (optional)Add <lastmod/> property. Default truetrue
exclude (optional)Array of relative paths (wildcard pattern supported) to exclude from listing on sitemap.xml or sitemap-*.xml. e.g.: ['/page-0', '/page-*', '/private/*'].

Apart from this option next-sitemap also offers a custom transform option which could be used to exclude urls that match specific patterns
string[]
sourceDir (optional)next.js build directory. Default .nextstring
outDir (optional)All the generated files will be exported to this directory. Default publicstring
transform (optional)A transformation function, which runs for each relative-path in the sitemap. Returning null value from the transformation function will result in the exclusion of that specific path from the generated sitemap list.async function
additionalPaths (optional)Async function that returns a list of additional paths to be added to the generated sitemap list.async function
generateIndexSitemapGenerate index sitemaps. Default trueboolean
generateRobotsTxt (optional)Generate a robots.txt file and list the generated sitemaps. Default falseboolean
robotsTxtOptions.transformRobotsTxt (optional)Custom robots.txt transformer function. (Example: custom-robots-txt-transformer)

Default: async(config, robotsTxt)=> robotsTxt
async function
robotsTxtOptions.policies (optional)Policies for generating robots.txt.

Default:
[{ userAgent: '*', allow: '/' }]
IRobotPolicy[]
robotsTxtOptions.additionalSitemaps (optional)Options to add additional sitemaps to robots.txt host entrystring[]
robotsTxtOptions.includeNonIndexSitemaps (optional)From v2.4x onwards, generated robots.txt will only contain url of index sitemap and custom provided endpoints from robotsTxtOptions.additionalSitemaps.

This is to prevent duplicate url submission (once through index-sitemap -> sitemap-url and once through robots.txt -> HOST)

Set this option true to add all generated sitemap endpoints to robots.txt

Default false (Recommended)
boolean

Custom transformation function

Custom transformation provides an extension method to add, remove or exclude path or properties from a url-set. Transform function runs for each relative path in the sitemap. And use the key: value object to add properties in the XML.

Returning null value from the transformation function will result in the exclusion of that specific relative-path from the generated sitemap list.

/** @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 ?? [],
    }
  },
}

Additional paths function

additionalPaths this function can be useful if you have a large list of pages, but you don't want to render them all and use fallback: true. Result of executing this function will be added to the general list of paths and processed with sitemapSize. You are free to add dynamic paths, but unlike additionalSitemap, you do not need to split the list of paths into different files in case there are a lot of paths for one file.

If your function returns a path that already exists, then it will simply be updated, duplication will not happen.

/** @type {import('next-sitemap').IConfig} */
module.exports = {
  additionalPaths: async (config) => {
    const result = []

    // required value only
    result.push({ loc: '/additional-page-1' })

    // all possible values
    result.push({
      loc: '/additional-page-2',
      changefreq: 'yearly',
      priority: 0.7,
      lastmod: new Date().toISOString(),

      // acts only on '/additional-page-2'
      alternateRefs: [
        {
          href: 'https://es.example.com',
          hreflang: 'es',
        },
        {
          href: 'https://fr.example.com',
          hreflang: 'fr',
        },
      ],
    })

    // using transformation from the current configuration
    result.push(await config.transform(config, '/additional-page-3'))

    return result
  },
}

Google News, image and video sitemap

Url set can contain additional sitemaps defined by google. These are Google News sitemap, image sitemap or video sitemap. You can add the values for these sitemaps by updating entry in transform function or adding it with additionalPaths. You have to return a sitemap entry in both cases, so it's the best place for updating the output. This example will add an image and news tag to each entry but IRL you would of course use it with some condition or within additionalPaths result.

/** @type {import('next-sitemap').IConfig} */
const config = {
  transform: async (config, path) => {
    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,
      images: [{ loc: 'https://example.com/image.jpg' }],
      news: {
        title: 'Article 1',
        publicationName: 'Google Scholar',
        publicationLanguage: 'en',
        date: new Date(),
      },
    }
  },
}

export default config

Full configuration example

Here's an example next-sitemap.config.js configuration with all options

/** @type {import('next-sitemap').IConfig} */

module.exports = {
  siteUrl: 'https://example.com',
  changefreq: 'daily',
  priority: 0.7,
  sitemapSize: 5000,
  generateRobotsTxt: true,
  exclude: ['/protected-page', '/awesome/secret-page'],
  alternateRefs: [
    {
      href: 'https://es.example.com',
      hreflang: 'es',
    },
    {
      href: 'https://fr.example.com',
      hreflang: 'fr',
    },
  ],
  // Default transformation function
  transform: async (config, path) => {
    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 ?? [],
    }
  },
  additionalPaths: async (config) => [
    await config.transform(config, '/additional-page'),
  ],
  robotsTxtOptions: {
    policies: [
      {
        userAgent: '*',
        allow: '/',
      },
      {
        userAgent: 'test-bot',
        allow: ['/path', '/path-2'],
      },
      {
        userAgent: 'black-listed-bot',
        disallow: ['/sub-path-1', '/path-2'],
      },
    ],
    additionalSitemaps: [
      'https://example.com/my-custom-sitemap-1.xml',
      'https://example.com/my-custom-sitemap-2.xml',
      'https://example.com/my-custom-sitemap-3.xml',
    ],
  },
}

Above configuration will generate sitemaps based on your project and a robots.txt like this.

# *
User-agent: *
Allow: /

# test-bot
User-agent: test-bot
Allow: /path
Allow: /path-2

# black-listed-bot
User-agent: black-listed-bot
Disallow: /sub-path-1
Disallow: /path-2

# Host
Host: https://example.com

# Sitemaps
Sitemap: https://example.com/sitemap.xml # Index sitemap
Sitemap: https://example.com/my-custom-sitemap-1.xml
Sitemap: https://example.com/my-custom-sitemap-2.xml
Sitemap: https://example.com/my-custom-sitemap-3.xml

Generating dynamic/server-side sitemaps

next-sitemap now provides two APIs to generate server side sitemaps. This will help to dynamically generate index-sitemap(s) and sitemap(s) by sourcing data from CMS or custom source.

  • getServerSideSitemapIndex: Generates index sitemaps based on urls provided and returns application/xml response. Supports next13+ route.{ts,js} file.

    • To continue using inside pages directory, import getServerSideSitemapIndexLegacy instead.
  • getServerSideSitemap: Generates sitemap based on field entires and returns application/xml response. Supports next13+ route.{ts,js} file.

    • To continue using inside pages directory, import getServerSideSitemapLegacy instead.

Server side index-sitemaps (getServerSideSitemapIndex)

Here's a sample script to generate index-sitemap on server side.

1. Index sitemap (app directory)

Create app/server-sitemap-index.xml/route.ts file.

// 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',
  ])
}
2. Index sitemap (pages directory) (legacy)

Create pages/server-sitemap-index.xml/index.tsx file.

// pages/server-sitemap-index.xml/index.tsx
import { getServerSideSitemapIndexLegacy } 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')

  return getServerSideSitemapIndexLegacy(ctx, [
    'https://example.com/path-1.xml',
   
项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

白日梦AI

白日梦AI提供专注于AI视频生成的多样化功能,包括文生视频、动态画面和形象生成等,帮助用户快速上手,创造专业级内容。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

讯飞绘镜

讯飞绘镜是一个支持从创意到完整视频创作的智能平台,用户可以快速生成视频素材并创作独特的音乐视频和故事。平台提供多样化的主题和精选作品,帮助用户探索创意灵感。

Project Cover

讯飞文书

讯飞文书依托讯飞星火大模型,为文书写作者提供从素材筹备到稿件撰写及审稿的全程支持。通过录音智记和以稿写稿等功能,满足事务性工作的高频需求,帮助撰稿人节省精力,提高效率,优化工作与生活。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号