NextJS Sitemap Example

Adding next-sitemap to the site was a breeze. It's easy to setup, fast, and makes managing sitemap.xml effortless.

Having a sitemap.xml file is important for SEO. It makes it easier for search engines to find and index your pages. I decided to add next-sitemap to this site for that reason. Here's how I did it.

Vercel

Installation

First, install the package:

npm install next-sitemap

or with yarn use yarn add next-sitemap

Adding next-sitemap.config.js

Next, create a next-sitemap.config.js file in the root of your project. next-sitemap will use this as a config file to generate your sitemap.xml files.

/** @type {import('next-sitemap').IConfig} */
module.exports = {
  siteUrl: process.env.NEXT_PUBLIC_SITE_URL || 'https://patebryant.com',
  generateRobotsTxt: true, // (optional)
}
More info on @type {import('next-sitemap').IConfig}

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

This is a JSDoc type annotation. It's job is to tell your editor what type of object module.exports is. Try removing the line and your editor will no longer autocomplete the config options.

Adding postbuild script

next-sitemap needs to be run after the site is built. By adding a postbuild script to package.json, we can run next-sitemap after the site is built. The postbuild script will run automatically after the build script is finished.

{
  "scripts": {
    "postbuild": "next-sitemap"
  }
}

Testing locally

Now that we have next-sitemap installed and configured, we can test it locally by running.

npm run build

Once the site is built you should see a sitemap.xml, sitemap-0.xml, and robots.txt file in the public folder.

Updating .gitignore (optional)

Because these files are only needed in production, we can add them to our .gitignore file. Otherwise if you don't always run npm run build before committing, you'll end up with sitemap files in your repo that are out of date.

public/robots.txt
public/sitemap*.xml

And that's it! Now that next-sitemap is installed and configured, it will automatically generate a new sitemap.xml file every time the site is built. Including when it is deployed to Vercel.