Company Logo

Bisht Bytes

How to Add Sitemap to Next.js 14

Published On: 20 Aug 2024
Reading Time: 3 minutes

Overview


Adding a sitemap to your Next.js 14 application is essential for SEO, ensuring that search engines can easily crawl and index your content. This guide walks you through the process of setting up a sitemap using the next-sitemap package, including configuration, automation, and custom sitemaps.

To add a sitemap to a Next.js 14 application, you can generate a sitemap dynamically during the build process or at runtime. Here's how you can do it:

Install Dependencies

First, you need to install the next-sitemap package, which is a popular solution for generating sitemaps in Next.js:

npm install next-sitemap --save-dev

Configure next-sitemap

Create a next-sitemap.config.js file in the root of your project with the following configuration:

/** @type {import('next-sitemap').IConfig} */
module.exports = {
  siteUrl: process.env.SITE_URL || 'https://yourdomain.com', 
  generateRobotsTxt: true, 
  changefreq: 'daily',
  priority: 0.7,
  sitemapSize: 7000,
};

Setting generateRobotsTxt to true, generates robots.txt file along with the sitemap.

Exclude paths

If you want to skip few paths, you can add another attribute to the next-sitemap.config.js file

/** @type {import('next-sitemap').IConfig} */
module.exports = {
  siteUrl: process.env.SITE_URL || 'https://yourdomain.com', 
  generateRobotsTxt: true, 
  changefreq: 'daily',
  priority: 0.7,
  sitemapSize: 7000,
  exclude: ["*/opengraph-image"],
};

Generate the Sitemap

You can now generate the sitemap using the following command:

npx next-sitemap

This will create a sitemap.xml file (and a robots.txt file if configured) in the public/ directory.

Automate Sitemap Generation (Optional)

To automate sitemap generation during the build process, you can add the npx next-sitemap command to your package.json scripts:

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

Now, every time you run npm run build, the sitemap will be generated automatically.

Accessing the Sitemap

Once everything is set up, you can access your sitemap at https://yourdomain.com/sitemap.xml.


Page Views: -