Generating Sitemap with next-sitemap - Modern Next.js Blog Series #18

Published on

This article is also published at it 邦幫忙 2022 iThome Ironman Contest

TL;DR

This is the 18th article in the "Modern Blog 30 Days" series. In the previous article, we configured site-wide meta data. Today, we'll use next-sitemap to generate a Sitemap, helping crawlers understand the website structure.

The code changes for this article are as follows:

https://github.com/Kamigami55/nextjs-tailwind-contentlayer-blog-starter/compare/day17-open-graph-meta...day18-sitemap


Adding a Sitemap

Another SEO detail that needs to be addressed is generating a Sitemap. A Sitemap is an XML file that lists all pages of a website, ensuring search engine crawlers don't miss any pages when indexing your site.

Sitemaps are typically located at a website’s /sitemap.xml path, for example, the Sitemap for this project is available at:

https://nextjs-tailwind-contentlayer-blog-starter.vercel.app/sitemap.xml

In Next.js, we can use next-sitemap to generate a Sitemap for us.

next-sitemap supports pages of all rendering strategies. And for our blog, where all pages are statically generated, no complex setup is required. next-sitemap can generate a Sitemap for us by analyzing the structure under /src/pages when executing pnpm build.

Installing next-sitemap

pnpm add -D next-sitemap

Add next-sitemap.config.js:

/** @type {import('next-sitemap').IConfig} */ module.exports = { siteUrl: "https://nextjs-tailwind-contentlayer-blog-starter.vercel.app", generateRobotsTxt: true, };

Modify the build script in package.json:

{ // ... "scripts": { // ... "build": "next build && next-sitemap --config next-sitemap.config.js" // ... } // ... }

Modify .gitignore, .eslintignore, .prettierignore to ignore the generated sitemap files:

# ... # Add the following 2 rules # Sitemap related files (generated by next-sitemap) /public/robots.txt /public/sitemap*.xml

Results

Done! After running pnpm build, you'll find sitemap.xml and robots.txt in the /public path.

The generated content includes:

public/robots.txt:

# * User-agent: * Allow: / # Host Host: https://nextjs-tailwind-contentlayer-blog-starter.vercel.app # Sitemaps Sitemap: https://nextjs-tailwind-contentlayer-blog-starter.vercel.app/sitemap.xml

public/sitemap.xml:

(Example XML content for sitemap.xml)

public/sitemap-0.xml:

(Example XML content for sitemap-0.xml)

After executing pnpm build, next-sitemap will also inform you that it has generated the Sitemap related files:

next-sitemap console output

The code changes for this article are as follows:

https://github.com/Kamigami55/nextjs-tailwind-contentlayer-blog-starter/compare/day17-open-graph-meta...day18-sitemap

References

Next Article

Having completed the Sitemap generation, the next article will deal with generating a very similar RSS feed!