Ads by ProfitSence
Close

Generate Sitemap for NextJS with the Sanity Client

Last Updated on Wednesday 5th Oct 2022

Sitemap Generation In NextJS with the Sanity Client.

A sitemap is an important for (SEO) because it makes it easier for Google,Yandex,Bing Search Engines to find your site’s pages.

Create the page with the name of sitemap.xml.js inside root directory.

			
					import groq from 'groq'
import client from './client'

export default function SiteMap() {
  return <div>loading</div>
}

export async function getServerSideProps({ res }) {
  const URL = https://codejagd.com
  const query = groq`{
      "posts": *[_type == 'post']{slug},
    }`
  const datas = await client.fetch(query)
  const posts = datas.posts.map(post => {
    const slug =
      post.slug.current === '/' ? '/' : /${post.slug.current}
    return `
      <loc>${URL}${slug}</loc>
      <changefreq>daily</changefreq>
      <priority>0.7</priority>
    `
  })

  const sitemapDatas = [...posts]
  const createSitemap = () => `<?xml version="1.0" encoding="UTF-8"?>
    <urlset 
      xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
        ${sitemapDatas
          .map(each => {
            return `<url>
                      ${each}
                    </url>
                  `
          })
          .join('')}
    </urlset>
    `
  res.setHeader('Content-Type', 'text/xml')
  res.write(createSitemap())
  res.end()
  return {
    props: {},
  }
}