front end code

Using next-sitemap to Generate Sitemaps


Sitemaps are vital for SEO; they help search engines better understand the structure and organization of your website, which can improve the ranking of your pages in search results. They’re essential to helping people find your website, and the next-sitemap npm package can help you easily set up sitemaps for your site.

Setting Up next-sitemap 

  • To install the package, go to the root of your Next.js application and run npm i next-sitemap
  • Add a postbuild script to your package.json file. This will run the next-sitemap command after npm run build is called. 
"scripts": {
    ...
    "postbuild": "next-sitemap",
  },
  • Create a config file called next-sitemap.config.js under the root of your application.
/** @type {import('next-sitemap').IConfig} */

module.exports = {
  siteUrl: process.env.YOUR_PUBLIC_URL || 'localhost:3000/',    
  generateRobotsTxt: true,	// optional: Creates a robots.txt file
};
  • Edit your .gitignore file to prevent automatically generated sitemap files from being added to your git repository. 
...
# sitemaps
public/robots.txt
public/sitemap*.xml
...

Generating Static Sitemaps

  • Run npm run build in your terminal to trigger the postbuild script. The output of the command should list the URLs of the sitemaps and sitemap indices. 
  • Run npm start and visit the URL outputted by the previous command (usually localhost:3000/sitemap-0.xml) to see the generated sitemap. 

Generating Sitemaps For Dynamic Routes

  • Create a new route.ts file under your app directory at app/server-sitemap.xml/route.ts
  • Write a GET request handler to return an array of all your dynamic URLs using the getServerSideSitemap function. 
// Example file 
import { getAllArticlesSlugs } from 'lib/CMS_client';
import { getServerSideSitemap } from 'next-sitemap';

export async function GET() {
  const URL = process.env.YOUR_PUBLIC_URL || 'localhost:3000/';

  const articleURLs = await getAllArticlesSlugs(); // replace with your own function that retrieves URLs
  const articles = articleURLs.map((slug) => ({
    loc: `${URL}articles/${slug}`,
    lastmod: new Date().toISOString(),
  }));

  return getServerSideSitemap(articles);
}

  • Edit your next-sitemap.config.js file to add your dynamic sitemap to your `robots.txt` file and exclude its URL from your appearing on your static sitemap.
/** @type {import('next-sitemap').IConfig} */

module.exports = {
  siteUrl: process.env.YOUR_PUBLIC_URL || 'localhost:3000/',    
  generateRobotsTxt: true,	
  exclude: ['/server-sitemap-index.xml'], // exclude dynamic sitemap URL from static sitemap
  robotsTxtOptions: {
    additionalSitemaps: [
      'https://example.com/server-sitemap-index.xml', // Tell robots.txt where your dynamic sitemap is
    ],
  },
};

After following these steps, your website’s sitemaps should be automatically generated every time npm run build is called. For more information and additional options, visit the next-sitemap documentation

Found this article interesting? Chat with our account specialists to get started on your next digital journey.