How to Create Sitemap on a Next.js Project with Hygraph CMS

Tutorial
Web Development
Blog
Studiofru
Studiofru
Cover Image for How to Create Sitemap on a Next.js Project with Hygraph CMS

What is Sitemap?

Google define sitemap as a file where you can provide information about pages, videos, and other files on a site, and the relationship between them which search engines like Google can read the file to crawl the site more efficiently. 

Search engines basically can discover most pages on the site without a sitemap file but sitemap can improve the crawling more efficiently especially if your site is a larger and a more complex site. To say the least, you might not need a sitemap if your site is small with only about 500 or fewer pages. 

A sitemap file generally consists of url links, the last modified date of the pages, the change frequency of the pages, and the priority of the pages. A sitemap file is a file written in eXtensible Markup Language (XML). With XML extension we can understand that sitemap is a file for storing and transporting the url navigation data of a website. 

How to Create a Sitemap?

There are some methods that you can do to create a sitemap file. You can always do it manually by writing down the code, save it as sitemap.xml and place it in the root of the app directory or in the pages directory in your Next.js project.  

Here is the sample code taken from Next.js documentation: 

app/sitemap.xml 

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://acme.com</loc>
    <lastmod>2023-04-06T15:02:24.021Z</lastmod>
    <changefreq>yearly</changefreq>
    <priority>1</priority>
  </url>
  <url>
    <loc>https://acme.com/about</loc>
    <lastmod>2023-04-06T15:02:24.021Z</lastmod>
    <changefreq>monthly</changefreq>
    <priority>0.8</priority>
  </url>
  <url>
    <loc>https://acme.com/blog</loc>
    <lastmod>2023-04-06T15:02:24.021Z</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.5</priority>
  </url>
</urlset>

 

If you want to generate it by exporting a default function you can do it like the sample code below:

app/sitemap.js

export default function sitemap() {
  return [
    {
      url: 'https://acme.com',
      lastModified: new Date(),
      changeFrequency: 'yearly',
      priority: 1,
    },
    {
      url: 'https://acme.com/about',
      lastModified: new Date(),
      changeFrequency: 'monthly',
      priority: 0.8,
    },
    {
      url: 'https://acme.com/blog',
      lastModified: new Date(),
      changeFrequency: 'weekly',
      priority: 0.5,
    },
  ]
}

If your site is a bit larger with dynamic pages such as those from CMS you must include the data that was fetched from the API. We are using Hygraph CMS for many of our sites and for this tutorial we are going to use the platform as our sample data.

First, inside the environment variable file, we need to include the API keys 

GRAPHCMS_PROJECT_API=<YOUR API KEY>
GRAPHCMS_PROD_AUTH_TOKEN=<YOUR PRODUCTION TOKEN>
GRAPHCMS_DEV_AUTH_TOKEN=<YOUR DEVELOPMENT TOKEN>
GRAPHCMS_PREVIEW_SECRET=<YOUR PREVIEW SECRET TOKEN>

Second, create hygraphcms.js in the lib directory and write the code as follows

async function fetchAPI(query, { variables, preview } = {}) {
  const res = await fetch(process.env.GRAPHCMS_PROJECT_API, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${
        preview
          ? process.env.GRAPHCMS_DEV_AUTH_TOKEN
          : process.env.GRAPHCMS_PROD_AUTH_TOKEN
      }`,
    },
    body: JSON.stringify({
      query,
      variables,
    }),
  })
  const json = await res.json()


  if (json.errors) {
    console.log(process.env.NEXT_EXAMPLE_CMS_GCMS_PROJECT_ID)
    console.error(json.errors)
    throw new Error('Failed to fetch API')
  
  return json.data
}


export async function getAllPostsWithSlug() {
  const data = await fetchAPI(`
    {
      posts () {
        slug
        updatedAt
      }
    }
  `)
  return data.posts
}

Then finally create sitemap.xml.js and put it in the app directory or pages directory and write down the code to generate the sitemap file such as follows

import { getAllPostsWithSlug } from 'lib/graphcms'

const Sitemap = () => {};

export const getServerSideProps = async ({ res }) => {
  const posts = await getAllPostsWithSlug()  
  const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>https://yoursite.com</loc>
        <lastmod>${new Date().toISOString()}</lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.5</priority>
    </url>  
    <url>
        <loc>https://yoursite.com/about</loc>
        <lastmod>${new Date().toISOString()}</lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.5</priority>
    </url>     
    ${posts.map(({ slug, updatedAt }) => `
    <url>
        <loc>https://yoursite.com/posts/${slug}</loc>
        <lastmod>${updatedAt}</lastmod>
        <changefreq>weekly</changefreq>
        <priority>1.0</priority>
    </url>
    `)
    .join('\n')}        
</urlset>
`;

  res.setHeader('Content-Type', 'text/xml');
  res.write(sitemap);
  res.end();

  return { props: {} };
}
  
export default Sitemap;

After you are done with the code writing you can build it with yarn build then yarn dev to see the sitemap file on your localhost at http://localhost:3000/sitemap.xml

You can always see the sample sitemap file by following the link below

External Link
Click here

Share this article