Next.js sitemap wrong on a Sanity site: missing pages and stale URLs
By Nayan Kyada · · 6 min read
Part of The Sanity + Next.js Guide
If your Next.js sitemap is wrong on a Sanity site, you will see it in Search Console first: new pages never get discovered, deleted pages keep getting crawled, or the sitemap lists URLs that redirect or 404. It is one of the quietest SEO bugs on a headless build, because the site looks fine to editors and the file nobody opens is the one that is broken.
This post covers the usual causes, in the order I check them, and how to confirm the fix. If your problem is that pages are in the sitemap but Google still refuses to index them, that is a different issue, covered in Next.js pages not indexed by Google.
What a wrong sitemap looks like
Open /sitemap.xml on the live domain and compare it with what editors have published. The symptoms fall into four groups:
- Recently published pages are absent for days or weeks.
- URLs for deleted or unpublished documents are still listed.
- URLs point to the wrong host, such as a staging or preview domain.
- Pages marked noindex, redirected pages, or empty template routes appear in the list.
Each group has a different cause, so do not rewrite the whole file before you know which one you have.
Cause 1: the sitemap was built once and never refreshed
A sitemap route with no dynamic data is rendered at build time and served as a static file. If the file queries Sanity but nothing triggers a rebuild or revalidation, it stays frozen at the last deploy. Editors publish ten pages, and the sitemap still reflects last month.
The fix is to tag the fetch so your publish webhook can invalidate it. If you already revalidate pages from Sanity, add the sitemap tag to the same handler. The webhook setup is in Sanity webhooks and Next.js ISR revalidation with HMAC verification, and batching is covered in Sanity webhook revalidation: batching tags.
Cause 2: the GROQ query filters too much or too little
This is the most common one. Someone wrote the query when the schema had three fields, and it has not changed since. Typical mistakes:
- Requiring a field such as a publish date that older documents never had, so they silently drop out.
- Querying only one document type and forgetting landing pages, case studies, or locale variants.
- Not excluding drafts, so URLs for unpublished work appear.
- Ignoring a noindex toggle in the SEO fields.
Here is the pattern I start from, in app/sitemap.ts:
// app/sitemap.ts
import type { MetadataRoute } from "next";
import { client } from "@/sanity/lib/client";
const BASE_URL = process.env.NEXT_PUBLIC_SITE_URL!;
const SITEMAP_QUERY = `*[
_type in ["page", "post", "caseStudy"] &&
defined(slug.current) &&
!(_id in path("drafts.**")) &&
coalesce(seo.noIndex, false) != true
]{
_type,
"slug": slug.current,
_updatedAt
}`;
const PREFIX: Record<string, string> = {
page: "",
post: "/blog",
caseStudy: "/work",
};
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const docs = await client.fetch<
{ _type: string; slug: string; _updatedAt: string }[]
>(SITEMAP_QUERY, {}, { next: { tags: ["sitemap"] } });
return docs.map((doc) => ({
url: `${BASE_URL}${PREFIX[doc._type] ?? ""}/${doc.slug}`,
lastModified: new Date(doc._updatedAt),
}));
}The coalesce matters: without it, documents that never had the noIndex field can be dropped by the comparison. Test the query in Vision inside Studio and count the results against the number of published documents you expect. If the numbers disagree, the query is your bug.
Cause 3: the wrong base URL
If the sitemap lists a staging host, an env var is wrong in production, or the build was made with a preview value. Check where NEXT_PUBLIC_SITE_URL comes from in each Vercel environment. Hardcoding a fallback to localhost or a vercel.app domain is a trap: it works in development and quietly ships. If the staging site itself ended up in search results, see staging site indexed by Google.
Cause 4: URL shapes that do not match the routes
The sitemap builds a path from the slug, but the route might differ. Examples I see on inherited projects:
- Slugs stored with a leading slash, producing double slashes.
- Trailing slash settings that disagree between the sitemap and the router.
- Locale-prefixed routes, where the sitemap lists unprefixed URLs.
- Slugs that were changed in Sanity, with the old URL redirected but the sitemap still emitting a stale value from another document that references it.
Every sitemap URL should return a 200 directly, with no redirect. A list full of redirected or 404 URLs trains Google to trust the file less. If you suspect broken routes, Next.js soft 404 errors on a Sanity site walks through the diagnosis, and slug changes causing 404s covers redirects.
Cause 5: the file is too big or has no index
One sitemap file can hold up to 50,000 URLs. Large catalogues or multilingual sites with many variants can pass that. Next.js has a generateSitemaps function in the sitemap file for splitting the output into several files. Check the current Next.js docs for the exact signature before you use it, because the arguments passed to the sitemap function changed in recent major versions. You also need robots.txt to point at the sitemap location, so confirm it with a quick look at /robots.txt.
How to verify the fix
- Count the URLs in /sitemap.xml and compare with the published document count from a GROQ count query in Vision.
- Publish a test page and confirm it shows up after your webhook fires, without a redeploy.
- Unpublish it and confirm it leaves the file.
- Crawl every sitemap URL with a crawler and check that each returns 200 with no redirect and no noindex tag.
- Submit the sitemap in Search Console and watch the discovered-URL count. Reading it takes a few days, so do not judge it the same afternoon.
What to ask a developer
If you hire someone to fix this, ask which document types are covered and why, how the sitemap is invalidated on publish, and how locales and noindex pages are handled. A good answer names the GROQ filter and the cache tag. A vague answer about regenerating on deploy means the same problem will return.
This is work I do as part of a Performance and Sanity audit, which starts from $800 and covers the sitemap, robots, redirects, and indexing checks together. For the wider picture of preserving rankings during changes, website redesign without losing SEO is the checklist I use.
Frequently asked questions
01Why is my Next.js sitemap missing Sanity pages?
Usually the GROQ query filters them out by accident, for example requiring a field that older documents lack, or the sitemap was statically generated at build time and never revalidated. Check the query in Vision first, then check how the sitemap is cached.
02Should draft documents appear in a sitemap?
No. Only published, indexable URLs that return a 200 status belong in a sitemap. Fetch with the published perspective and exclude any document marked noindex.
03How many URLs can one sitemap file hold?
The sitemap protocol allows up to 50,000 URLs or 50 MB uncompressed per file. Larger sites split into several sitemaps listed from a sitemap index, and Next.js has generateSitemaps for that.