How to Create a Sitemap in Next.js 13?

The Sitemap is an XML file that notifies search engines like Google about the structure and content of the website. This would helps search engines to discover and index the pages efficiently which improve the website SEO (Search Engine Optimization).

Prerequisites

These are the following approaches:

Table of Content

  • Static Sitemap
  • Dynamic Sitemap (Recommended)

Steps to Create Next JS Application

Step 1: Create a NextJS application using the following command

npx create-next-app my-app

Step2: Navigate to my-app folder using cd command

cd my-app

Step3: Run the following command to start development server

npm run dev

Project Structure:

The updated dependencies in package.json file will look like:

{
"dependencies": {
"next": "^13.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"next-sitemap": "^3.2.0" // Added for dynamic sitemap
}
}

Static Sitemap

  • Static sitemaps are Suitable for small websites with relatively static content. You manually list all URLs in an XML file.

Steps to create Static sitemap

  • Create a file named sitemap.xml in the app directory.
  • Use XML syntax to list your website URLs.
  • Update the loc attribute with each page’s URL and the lastmod attribute (optional) with the last modification date (ISO 8601 format).
  • Manually maintain this file as your website grows.

Example: This example shows the static sitemap.

XML
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns=
"http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://your-website.com/</loc>
    <lastmod>2024-06-09T00:00:00Z</lastmod>
  </url>
  </urlset>

Dynamic Sitemap (Recommended)

  • Dynamic sitemaps are ideal for larger websites with dynamic content. You write code to generate the sitemap automatically based on your application data.

Steps to create Dynamic sitemap

  • Install the next-sitemap package
npm install next-sitemap
  • Create a file named sitemap.xml.js or sitemap.xml.ts (depending on your preference) in the app directory
  • Import and use the sitemap function from next-sitemap

Example: This example shows the Dynamic sitemap.

JavaScript
import { Sitemap } from 'next-sitemap';

export default async function handler() {
  try {
    // Replace with logic to fetch or 
    // generate your website URLs dynamically
    const urls = [];
    const fs = require('fs');
    // Replace with your directory path
    const pagesDirectory = './pages'; 

    if (fs.existsSync(pagesDirectory)) {
      const files = fs.readdirSync(pagesDirectory);
      for (const file of files) {
        if (file !== 'sitemap.xml.js' && !file.startsWith('_'))
          { // Exclude this file and hidden files
           // Extract slug from filename
          const slug = file.replace(/\.jsx?$/, '');
          urls.push({
            loc: `https://your-website.com/${slug}`,
          });
        }
      }
    }

    return Sitemap(urls).toXML();
  } catch (error) {
    console.error('Error generating sitemap:', error);
    // Handle errors gracefully (e.g., return an empty sitemap or log the error)
    // Return an empty sitemap to avoid server crashes
    return Sitemap([]).toXML(); 
  }
}

Output:

Output

The benefits of using Sitemap

  • Improved Indexing:  A sitemap acts like a roadmap for search engines like Google,  letting them know about all the pages on your website.
  • SEO Efficiency:  Sitemaps provide search engines with valuable information beyond just URLs. You can specify priority levels for different pages and update frequencies, giving search engines a better understanding of the importance of various sections of your site.
  • Faster Discovery of New Content: With a dynamic sitemap, whenever you add new pages to your Next.js website, the sitemap automatically updates to reflect the changes.

Conclusion

For websites with relatively static content (few changes), a static sitemap is a simple, manual solution. You create an XML file with the URLs of your main pages and update it whenever necessary and for larger websites with dynamic content or frequent updates, a dynamic sitemap (using next-sitemap) is more efficient. This will automatically generates the sitemap for the website, ensuring it’s always up-to-date with your content.



Contact Us