Sitemaps with next.js and sanity.io

Nognom.com Sitemaps

Nognom.com Sitemaps, by: Michael Mongon

SEO and sitemaps. We’ve all heard the debate and at various times I’ve been on both sides of the fence. Mostly, I dislike the advice from an SEO consultant because it is the simplest and most basic advice any SEO expert can give. Google has become sophisticated in it’s searches and if your site is not complex it can find the pages easily. However, a sitemap does give a clean and straightforward signal to the pages you find valuable. In short, it’s important, but I don’t think there is evidence that it is the most important signal to focus on.

What is a Sitemap?

A sitemap is a file that lists all the pages of a website to inform search engines about the content. It contains URLs along with additional metadata such as the last modification date, change frequency, and priority of each page. Sitemaps come in various formats, including XML and HTML, and serve as a roadmap for search engine crawlers to navigate and index a website efficiently.

Why Build a Sitemap?

Improved Crawling and Indexing: Sitemaps provide search engines with a comprehensive list of URLs, ensuring that all pages are discovered and indexed promptly. This can be especially valuable for large websites with complex structures or dynamic content.

Better Page Prioritization: By specifying the priority and change frequency of each page in the sitemap, website owners can signal to search engines which content is most important or frequently updated. This helps search engines prioritize crawling and indexing accordingly.

The Skeptic's View

Despite the advantages, the true impact of sitemaps on search engine rankings is often debated:

Limited Influence on Rankings: While sitemaps facilitate crawling and indexing, they are just one of many factors that search engines consider when ranking websites. The quality and relevance of content, backlinks, site speed, and user experience often carry more weight in determining search engine rankings.

Not a top priority: Generating a sitemap alone is unlikely to bring a website to the top of search results. It should be part of a broader SEO strategy that addresses multiple aspects of website optimization, including content quality, technical SEO, and off-page factors.

Google's Sophistication: Search engines like Google have become increasingly sophisticated in crawling and understanding website structures. While sitemaps can be helpful for large or complex sites, Google's algorithms can often discover and index pages without relying solely on sitemap data.

How To Implement a Sitemap With Next.js and Sanity?

You will find an infinite number of examples on the internet, but here's mine to share.

Nognom's Example: https://www.nognom.com/api/sitemap.xml

You need to start by collecting what pages you want to generate a sitemap with. You will inevitably find some pages you will just hand code, but you don’t want to commit a new line of code each time you make content in your CMS. Here we will follow how I created some quick automation within next.js so that once content is published I don't need to add another url by hand. That would be a waste of time to remember. Sitemaps should largely be built and forgotten.

At this point, you should already know how to build your GROQ for sanity, so things like setting up your client should be familiar to you. Reach out if you are stuck there, I might be able to help. Create a file '//pages/api/sitemap.xml.js':

sitemap.xml.js

Sitemap file code generation by: Michael Mongon

import { getSitemap } from'../../lib/sitemap'; // Import a function export default async function handler(req, res) { try { constsitemap=awaitgetSitemap(); // Generate the sitemap res.setHeader('Content-Type', 'text/xml'); res.write(sitemap); res.end(); } catch (error) { console.error('Error generating sitemap:', error); res.status(500).end(); } }

Create a file '//lib/sitemap.js':

This file has your sanity client your GROQ and the function called from sitemap.xml.js.

sitemap function

sitemap function by: Michael Mongon

import { createClient } from'@sanity/client'; constclient=createClient({ projectId:'YOURID', dataset:'YOURDATASET', token:YOURTOKEN, useCdn:true, apiVersion:'2021-08-31' }) export async function getSitemap() { constbase_url='https://YOURDOMAIN'; try { const postData=awaitclient.fetch(postQuery); constsitemap=`<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"> <url><loc>ADD ANY MANUAL LINKS HERE</loc><changefreq>weekly</changefreq><priority>0.7</priority></url> ${postData.map(({ slug, _updatedAt }) =>`<url> <loc>${base_url}/posts/${slug.current}</loc> <lastmod>${newDate(_updatedAt).toISOString()}</lastmod> <changefreq>weekly</changefreq> <priority>0.8</priority> </url>`).join('')} </urlset>`; returnsitemap; } catch (error) { console.error('Error generating sitemap:', error); throw error; } } export const postQuery=` *[_type == "post" && !(_id in path("drafts.*"))] | order(publishedAt asc) { _id, slug, _updatedAt, }`; You will likely have a longer 'postQuery' in your actual page. Save your processing and only pull the slug and the updated date back.

Conclusion: Sitemaps Are Only A Piece of the SEO Puzzle

I hope you enjoyed the simple example of how to build a sitemap in next.js and sanity. It's not the most important part of SEO. For you too, I hope it's something you can set up and forget. Don't forget to add the link to your robots file and submit it to Search Console. Let Google and Bing tell you when there is an issue and you need an update.