BLOG ON

Dynamic Sitemap in Next.js

UPDATED ON - 19th May, 2024

PUBLISHED BY

Aditya Prem Sharma

Aditya Prem Sharma

Frontend Developer


Table of Contents

Introduction

In Next.js, generating a dynamic sitemap involves creating an endpoint that generates the sitemap dynamically based on your website's content. You can achieve this by using the getServerSideProps or getInitialProps functions in your Next.js pages to fetch data and generate the sitemap.

Implementation

Here's what you need to create a dynamic sitemap in Next.js. Inside pages folder create a file named exactly sitemap.xml.js, so the path where you will create this file would be:


project -> pages -> sitemap.xml.js

Now let's implement the code for sitemap.xml.js file:

JS CODE

function generateSiteMap(data) {
  const xmlUrls = data.map((item) => {
      return `
      <url>
        <loc>${item.path}</loc>
        <lastmod>${item.date}</lastmod>
        <changefreq>monthly</changefreq>
        <priority>1</priority>
      </url>
    `;
    })
    .join("");

  return `<?xml version="1.0" encoding="UTF-8"?>
   <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
     
     <url>
       <loc>https://www.softwarestudiopro.com</loc>
       <lastmod>2024-01-20</lastmod>
       <changefreq>monthly</changefreq>
       <priority>1</priority>
     </url>
     <url>
       <loc>https://www.softwarestudiopro.com/contact-us</loc>
       <lastmod>2024-01-20</lastmod>
       <changefreq>monthly</changefreq>
       <priority>1</priority>
     </url>
      ${xmlUrls}
   </urlset>
 `;
}

function SiteMap() {
  // getServerSideProps will do the heavy lifting, no need to do anything here
}

export async function getServerSideProps({ res }) {
  // We make an API call / create a dataset to gather the URLs for our site
    const request = await fetch(EXTERNAL_DATA_URL);
    const data = await request.json();

  // We generate the XML sitemap with the data assuming we get an array as a response in data 
  const sitemap = generateSiteMap(data);
  res.setHeader("Content-Type", "text/xml");

  // we send the XML to the browser
  res.write(sitemap);
  res.end();

  return {
    props: {},
  };
}

export default SiteMap;

And voila! You're all set now. You're sitemap will be generated. You can check it out by navigating on the path /sitemap.xml


Go to -> http://localhost:3000/sitemap.xml
Or for hosted app, go to -> https://www.yourwebsite.com/sitemap.xml



You will see some XML code appear in your browser (similar to the one below) with all the links you have generated.

XML CODE

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://www.softwarestudiopro.com</loc>
    <lastmod>2024-01-20</lastmod>
    <changefreq>monthly</changefreq>
    <priority>1</priority>
  </url>
  <url>
    <loc>https://www.softwarestudiopro.com/contact-us</loc>
    <lastmod>2024-01-20</lastmod>
    <changefreq>monthly</changefreq>
    <priority>1</priority>
  </url>
</urlset>

Conclusion

In this blog, we implemented sitemap for our Next.js app. Remember to update the data array and generateSitemap function according to your application's specific requirements and data sources. Additionally, you might want to consider caching strategies for performance optimization, especially if your content doesn't change frequently.

Ready to bring your business idea to life? Contact us today and let's build something amazing together!

Contant Us