How to generate sitemap for NextJs Projects

03-Aug-20201 Min Read

Nextjs is the best framework out there to create server side rendered react apps. Now with the support of pre-rendered pages and static export, its on the way to become ultimate tool for both dynamic and static content generation.

Sitemaps are important requirement for generating good SEO. It provides the information to search engines about your website and what urls to crawl.

NextJS doesn't provide native support for sitemap generation. So our best option is to write a custom solution or use an existing packages like next-sitemap. (PS: I'm the author of this package)

Source Code#

  • Documentation

  • Example Project

Summary#

In this tutorial we will create a nextjs app that generates 10000+ pre-rendered pages and create sitemaps and robots.txt for the generated contents.

Project Setup#

Let's start by creating a sample next.js project. You can skip this setup, if you already have an existing project.

Now lets create an index page and pre-rendered page.

Add the NextJs build script

Let's also add a pre-rendered page which will generate 10000 static pages.

We are now ready to add the sitemap generator package to our project.

Add next-sitemap package#

Add next-sitemap with

next-sitemap requires a basic configuration file under your project root. Create next-sitemap.js with following contents.

Add postbuild script on package.json for triggering sitemap generate every time our project gets build.

Congrats!! Now you are ready to build your project and dynamically create sitemaps and robots.txt. Let's move on to building the project.

Build the project#

Now there is a public directory with robots.txt, sitemap.xml & sitemap-*.xml. These sitemaps contains absolute links to all static and pre-rendered pages and they are being split into chunks of 5000 links per file.

Generated robots.txt will look like this.

More

For additional configurations such as user-agent policies, custom-sitemaps, chunk-size etc. Please check the next-sitemap Documentation