Files
supabase/apps/docs/internals/generate-sitemap.ts
Miranda LimonczenkoandClaude 4d9726da1c feat(docs): add last-modified dates to the docs sitemap (#54329)
Closes DOCS-1753

## Problem

Guide pages already show a "Last updated" date
(supabase/supabase#52421), but `sitemap.xml` has no `<lastmod>`, so
crawlers get no recency signal.
## Solution

- Guide entries in `sitemap.xml` now include `<lastmod>`. The date comes
from the same `last_changed` table as the on-page date: the newest
`last_updated` across a page's sections, written as an ISO 8601
timestamp.
- The paginated `last_changed` read moved from `lib/last-changed.ts`
into `lib/last-changed.utils.ts`. The new module has no `server-only`
import, so the `tsx` sitemap script can share it. `getGuideLastUpdated`
behaves the same, including its timeout, cooldown, and Sentry reporting.
- When `NEXT_PUBLIC_SUPABASE_URL` or `SUPABASE_SECRET_KEY` is missing,
or the read fails, the script logs a warning and writes the sitemap
without `<lastmod>`. Local and preview builds still succeed.
- `build:sitemap` in `apps/docs/turbo.jsonc` is now uncached and passes
the two credentials through. The dates change nightly, outside the
task's inputs, so a cache hit could otherwise restore stale dates. The
task is cheap, and its dependencies stay cached.
- Reference pages don't get `<lastmod>` because `last_changed` only
tracks guides.
- `sitemap.md` (marked TBD in the issue) is out of scope.

## Review instructions

| Preview | Link |
| --- | --- |
| Docs sitemap |
https://docs-git-claude-compassionate-dirac-ns0vjr-supabase.vercel.app/docs/sitemap.xml
|
| Docs app |
https://docs-git-claude-compassionate-dirac-ns0vjr-supabase.vercel.app/docs
|

1. Check the `build:sitemap` step in the Vercel build log. It should
print `Total of N pages in sitemap (M with last-modified dates)`, where
M is greater than 0.
2. In the preview deploy, open `/docs/sitemap.xml` and confirm that
guide entries have `<lastmod>` values matching the "Last updated" date
on those pages.
3. Optional local check: run `pnpm -F docs build:sitemap` without
credentials. You should see the warning, and the sitemap should have no
`<lastmod>` entries.

Co-authored-by: Claude <noreply@anthropic.com>
2026-12-01 10:03:01 -08:00

112 lines
3.6 KiB
TypeScript

/*
* kudos to leerob from vercel
* https://leerob.io/blog/nextjs-sitemap-robots
*/
import { createClient } from '@supabase/supabase-js'
import fs from 'fs'
import { globby } from 'globby'
import matter from 'gray-matter'
import { format } from 'oxfmt'
import { checkGuidePageEnabled } from '~/features/docs/NavigationPageStatus.utils'
import { fetchGuidePageDates } from '~/lib/last-changed.utils'
import { type Database } from '~/lib/supabase'
import { generateReferencePages } from './files/reference-lib'
const LOOKUP_TIMEOUT_MS = 30_000
/**
* Loads each guide's last content change from the `last_changed` table, the
* same source as the "Last updated" date on guide pages. Returns an empty map
* when credentials are missing or the read fails, so the sitemap still builds
* (without `<lastmod>`) in local and preview environments.
*/
async function loadGuideDates(): Promise<Map<string, string>> {
const url = process.env.NEXT_PUBLIC_SUPABASE_URL
const key = process.env.SUPABASE_SECRET_KEY
if (!url || !key) {
console.warn('Supabase credentials not set, so the sitemap omits last-modified dates')
return new Map()
}
try {
return await fetchGuidePageDates(
createClient<Database>(url, key),
AbortSignal.timeout(LOOKUP_TIMEOUT_MS)
)
} catch (error) {
console.warn('Failed to load last-modified dates, so the sitemap omits them:', error)
return new Map()
}
}
async function generate() {
const [referencePages, guideDates] = await Promise.all([
generateReferencePages(),
loadGuideDates(),
])
const contentFiles = await globby(['content/guides/**/!(_)*.mdx'])
const contentPages = await Promise.all(
contentFiles.map(async (filePath) => {
const fileContents = await fs.promises.readFile(filePath, 'utf8')
const {
data: { sitemapPriority },
} = matter(fileContents)
const lastUpdated = guideDates.get(`/${filePath}`)
return {
link: filePath.replace(/^content\//, '').replace(/\.mdx$/, ''),
priority: sitemapPriority ?? 0.8,
lastmod: lastUpdated ? new Date(lastUpdated).toISOString() : undefined,
}
})
)
const allPages = (contentPages as Array<{ link: string; priority: number; lastmod?: string }>)
.filter(({ link }) => checkGuidePageEnabled(`/${link}`))
.concat(referencePages)
// Keep the output order stable across builds
allPages.sort((a, b) => (a.link < b.link ? -1 : a.link > b.link ? 1 : 0))
const sitemap = `
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${allPages
.map(({ link, priority, lastmod }) => {
const finalPriority = priority ?? 0.8
return `
<url>
<loc>${`https://supabase.com/docs/${link}`}</loc>${lastmod ? `\n<lastmod>${lastmod}</lastmod>` : ''}
<changefreq>weekly</changefreq>
<priority>${finalPriority}</priority>
</url>
`
})
.join('')}
</urlset>
`
const { code: formatted, errors } = await format('sitemap.html', sitemap, {
tabWidth: 2,
printWidth: 100,
endOfLine: 'lf',
})
if (errors.length > 0) {
throw new Error(`Failed to format docs sitemap: ${errors.map((e) => e.message).join('; ')}`)
}
const sitemapFilePath = `public/sitemap.xml`
const datedCount = allPages.filter((page) => page.lastmod).length
console.log(
`Total of ${allPages.length} pages in sitemap (${datedCount} with last-modified dates), located at /apps/docs/${sitemapFilePath}`
)
fs.writeFileSync(sitemapFilePath, formatted)
}
generate()