How to create Sitemap for your NEXTJS website ?

Sitemaps tell google about all the pages that you wanna have indexed in google search.

According to NEXTJS, Sitemaps are the easiest way to communicate with Google. They indicate the URLs that belong to your website and when they update so that Google can easily detect new content and crawl your website more efficiently.

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://example.com/</loc>
    <lastmod>2024-10-25</lastmod>
    <priority>1.0</priority>
  </url>
  <url>
    <loc>https://example.com/about</loc>
    <lastmod>2024-10-20</lastmod>
    <priority>0.8</priority>
  </url>
</urlset>

THIS WAS YOUR STATIC SITEMAP.

According to NEXTJS, Static sitemaps are also valid, but they might be less useful to Google as it won’t serve for constant discovery purposes.

Notes:

  • that <loc> means the location of the URL.

Now For Dynamic Sitemap:

// pages/sitemap.js.xml

import axios from 'axios'

const EXT_URL= 'https://jsonplaceholder.typicode.com/posts'

function generateSitemap(){
  return `<?xml version="1.0" encoding="UTF-8"?>
   <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
     <!--We manually set the two URLs we know already-->
     <url>
       <loc>https://jsonplaceholder.typicode.com</loc>
     </url>
     <url>
       <loc>https://jsonplaceholder.typicode.com/guide</loc>
     </url>
     ${posts
       .map(({ id }) => {
         return `
       <url>
           <loc>${`${EXTERNAL_DATA_URL}/${id}`}</loc>
       </url>
     `;
       })
       .join('')}
   </urlset>
 `;
}

function SiteMap() {
  // getServerSideProps will do the heavy lifting
}

export async function getServerSideProps({ res }) {
  // We make an API call to gather the URLs for our site
  const request = await fetch(EXTERNAL_DATA_URL);                 // HERE REPLACE THE FETCH CALL WITH 
  const posts = await request.json();

  // We generate the XML sitemap with the posts data
  const sitemap = generateSiteMap(posts);

  res.setHeader('Content-Type', 'text/xml');
  // we send the XML to the browser
  res.write(sitemap);
  res.end();

  return {
    props: {},
  };
}

export default SiteMap;

2. Why sitemap.xml.js?

We name the file sitemap.xml.js because we want the sitemap to be accessible from the URL path /sitemap.xml. So, by placing the file inside the pages directory as sitemap.xml.js, it makes the sitemap available at:

https://yourwebsite.com/sitemap.xml