Generate a Comprehensive Sitemap with Next-Sitemap for Better SEO Results

2023-19-02|2 min read
Learn how to create a comprehensive sitemap for your Next.js web application and improve your SEO with Next-Sitemap library. In this step-by-step tutorial, we'll guide you through the process of installing and using Next-Sitemap to generate a sitemap of all your website pages. Maximize your website's visibility and search engine rankings with Next-Sitemap.

Next.js is a popular framework for building React applications. It offers many features out of the box, including server-side rendering, automatic code splitting, and optimized performance. However, when it comes to creating a sitemap for your Next.js app, you'll need to use a library. That's where Next-Sitemap comes in.

What is Next-Sitemap?

Next-Sitemap is a library that generates a sitemap for your Next.js application. It's built on top of the popular sitemap.js library, which provides a flexible and extensible way to generate sitemaps. Next-Sitemap takes care of the configuration and setup required to generate a sitemap, so you don't have to worry about the technical details.

How to Use Next-Sitemap

Using Next-Sitemap is straightforward. First, you'll need to install it in your Next.js project:

npm install next-sitemap

Next, create a next-sitemap.config.js file in the root directory of your project. This file will contain the configuration options for your sitemap. Here's an example configuration:

module.exports = {
  siteUrl: 'https://example.com',
  generateRobotsTxt: true,
};

Advanced Usage

module.exports = {
  siteUrl: 'https://example.com',
  generateRobotsTxt: true,
  exclude: ['/admin/**', '/api/**'],
  robotsTxtOptions: {
    additionalSitemaps: [
      'https://example.com/sitemap1.xml',
      'https://example.com/sitemap2.xml',
    ],
  },
};

Let's go through each of these options:

  • siteUrl: The URL of your website. This is required for the sitemap to be generated.
  • generateRobotsTxt: Whether to generate a robots.txt file. This is optional and defaults to false.
  • exclude: An array of paths to exclude from the sitemap. This is optional and defaults to [].
  • robotsTxtOptions: An object containing additional options for the robots.txt file. This is optional and defaults to {}.

Adding Commands to package.json

{
  "scripts": {
    "build": "next build",
    "start": "next start",
    "export": "next export",
    "postbuild": "next-sitemap"
  }
}

Generate Sitemap On Build

Sitemap and robots files will be automatically created under the public folder where you run the npm run build command.

Conclusion

Creating a sitemap is an important part of optimizing your website for search engines. With Next-Sitemap, generating a sitemap for your Next.js app is simple and straightforward. By using the configuration options and advanced features provided by Next-Sitemap, you can ensure that your site is fully indexed and easily discoverable by search engines.