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:
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
Copied!pnpm add -D next-sitemap
Add next-sitemap.config.js
:
Copied!/** @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
:
Copied!{ // ... "scripts": { // ... "build": "next build && next-sitemap --config next-sitemap.config.js" // ... } // ... }
Modify .gitignore
, .eslintignore
, .prettierignore
to ignore the generated sitemap files:
Copied!# ... # 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
:
Copied!# * 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:
The code changes for this article are as follows:
References
Next Article
Having completed the Sitemap generation, the next article will deal with generating a very similar RSS feed!