ScottSpence.com

Scott's Thoughts Pamphlet!

🤫This is a private post👀

Sitemap Generation for Dynamic Routes In NextJS with the Sanity Client

1import groq from 'groq'
2import sanityClient from '../sanity-client'
3
4export default function SiteMap() {
5 return <div>loading</div>
6}
7
8export async function getServerSideProps({ res }) {
9 const baseUrl = `https://promotebritain.co.uk`
10 const query = groq`{
11 "countries": *[_type == 'country']{slug},
12 "counties": *[_type == 'county']{slug},
13 }`
14 const urls = await sanityClient.fetch(query)
15 const countries = urls.countries.map(page => {
16 const slug =
17 page.slug.current === '/' ? '/' : `/${page.slug.current}`
18 return `
19 <loc>${baseUrl}${slug}</loc>
20 <changefreq>daily</changefreq>
21 <priority>0.7</priority>
22 `
23 })
24 const counties = urls.counties.map(page => {
25 const slug =
26 page.slug.current === '/' ? '/' : `/${page.slug.current}`
27 return `
28 <loc>${baseUrl}${slug}</loc>
29 <changefreq>daily</changefreq>
30 <priority>0.7</priority>
31 `
32 })
33 const locations = [...countries, ...counties]
34 const createSitemap = () => `<?xml version="1.0" encoding="UTF-8"?>
35 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
36 ${locations
37 .map(location => {
38 return `<url>
39 ${location}
40 </url>
41 `
42 })
43 .join('')}
44 </urlset>
45 `
46 res.setHeader('Content-Type', 'text/xml')
47 res.write(createSitemap())
48 res.end()
49 return {
50 props: {},
51 }
52}

Back to Top


Scott Spence

Built with Gatsby · Hosted on Vercel · 2021