fix: HTML sitemap pages once per locale, never over a catch-all by default

- seoSitemapPages (lib/sitemapPages.ts) builds the routes per locale; the
  module adds them from a pages:resolved hook registered on ready, after
  @nuxtjs/i18n has localised the app's routes, so no cross-locale copies
  exist and each name ends in the locale's i18n suffix (L4 WR-05)
- a path an app catch-all covers is left to it and logged at build unless
  seo.htmlSitemap.overCatchAll is true (L4 WR-04)
- SitemapLink falls back to the i18n locale and renders only when the path
  resolves to the layer's sitemap page of that locale
- an app with only app.vue no longer gets its router turned on by the pages
This commit is contained in:
Jakub Zych
2026-11-04 22:47:58 +01:00
parent 7588aa53b0
commit a651de4675
8 changed files with 270 additions and 34 deletions

View File

@@ -8,7 +8,12 @@ export interface SeoPaginationOption {
segments: Record<string, string>
}
export type SeoHtmlSitemapOption = { paths: Record<string, string> } | false
/**
* The HTML sitemap pages by locale, or false for none. overCatchAll: serve
* the layer's pages ahead of an app catch-all page that covers the path
* (default false: the catch-all keeps the path, L4 WR-04).
*/
export type SeoHtmlSitemapOption = { paths: Record<string, string>; overCatchAll: boolean } | false
/** The pagination option with its defaults, as the runtime config carries it. */
export function paginationOption(value: unknown): SeoPaginationOption {
@@ -23,7 +28,7 @@ export function paginationOption(value: unknown): SeoPaginationOption {
}
}
/** The HTML sitemap option: false, or the paths (each '/' plus at least one character). */
/** The HTML sitemap option: false, or the paths (each '/' plus at least one character) and overCatchAll. */
export function htmlSitemapOption(value: unknown): SeoHtmlSitemapOption {
if (value === false) return false
const v = value !== null && typeof value === 'object' ? (value as Record<string, unknown>) : {}
@@ -32,5 +37,5 @@ export function htmlSitemapOption(value: unknown): SeoHtmlSitemapOption {
for (const [locale, path] of Object.entries(raw)) {
if (typeof path === 'string' && /^\/[^?#\s]+$/.test(path) && !path.includes(':') && !path.includes('*')) paths[locale] = path.replace(/\/+$/, '')
}
return { paths }
return { paths, overCatchAll: v.overCatchAll === true }
}

View File

@@ -9,10 +9,11 @@
// options never use a name nuxt-seo-utils has (enabled, fallbackTitle …).
import { fileURLToPath } from 'node:url'
import { addServerTemplate, defineNuxtModule, extendPages, useLogger } from 'nuxt/kit'
import { addServerTemplate, defineNuxtModule, useLogger } from 'nuxt/kit'
import { findOffenders, guardMessage, noindexRule, type GuardPage } from './guard.ts'
import { htmlSitemapOption, paginationOption, type SeoHtmlSitemapOption, type SeoPaginationOption } from './options.ts'
import { localeCopySuffixes, noindexStaticRoutes, routePatterns, routesTemplate, staticRoutes, type RoutePage } from './routes.ts'
import { isSitemapRoute, seoSitemapPages, sitemapSkipMessage } from './sitemapPages.ts'
export interface SeoModuleOptions {
/**
@@ -64,7 +65,9 @@ export interface SeoModuleOptions {
/**
* The HTML sitemap pages (D-34), by locale: the overview at the path, a
* group at <path>/<group>. false registers none. A path an app page
* already has is left to the app.
* already has is left to the app, and so is a path an app catch-all page
* covers unless overCatchAll is true. With @nuxtjs/i18n each locale's
* pages exist once, at its configured path.
*/
htmlSitemap: SeoHtmlSitemapOption
}
@@ -151,27 +154,32 @@ export default defineNuxtModule<SeoModuleOptions>({
guard()
})
// The HTML sitemap pages (D-34, P33-32), one overview and one group
// page per locale, each rendering the global SeoHtmlSitemapPage. A path
// an app page already has stays the app's.
// The HTML sitemap pages (D-34, P33-32, P33-68), one overview and one
// group page per locale, each rendering the global SeoHtmlSitemapPage
// (lib/sitemapPages.ts). Added in a pages:resolved hook that runs after
// @nuxtjs/i18n has localised the app's routes, in either scanPageMeta
// mode, so i18n never copies these routes into other locales (L4 WR-05).
// i18n registers its page hook from its modules:done handler, which runs
// after this module's (this layer's module is set up first), so the hook
// is registered on ready: Nuxt calls it once every modules:done handler
// has run and before the build resolves the pages. A path an app page
// already has stays the app's, a path an app catch-all covers stays the
// catch-all's unless htmlSitemap.overCatchAll is true (L4 WR-04).
if (htmlSitemap !== false) {
const overviewFile = fileURLToPath(new URL('../app/seo-pages/SitemapPage.vue', import.meta.url))
const groupFile = fileURLToPath(new URL('../app/seo-pages/SitemapGroupPage.vue', import.meta.url))
extendPages((list) => {
const taken = new Set(list.map((p) => p.path))
for (const [locale, path] of Object.entries(htmlSitemap.paths)) {
if (taken.has(path)) {
logger.info(`HTML sitemap: the app has its own page at ${path}; the layer's ${locale} sitemap page is not registered`)
continue
}
const meta = { seoSitemap: { locale } }
list.push({ name: `seo-sitemap-${locale}`, path, file: overviewFile, meta })
list.push({ name: `seo-sitemap-group-${locale}`, path: `${path}/:group`, file: groupFile, meta })
if (pagination.form === 'path') {
const segment = pagination.segments[locale] || pagination.param
list.push({ name: `seo-sitemap-group-page-${locale}`, path: `${path}/:group/${segment}/:page(\\d+)`, file: groupFile, meta })
}
}
const files = {
overview: fileURLToPath(new URL('../app/seo-pages/SitemapPage.vue', import.meta.url)),
group: fileURLToPath(new URL('../app/seo-pages/SitemapGroupPage.vue', import.meta.url)),
}
nuxt.hook('ready', () => {
nuxt.hook('pages:resolved', (resolved) => {
const list = resolved as unknown as RoutePage[]
// A dev regeneration may hand back the routes added before.
for (let i = list.length - 1; i >= 0; i--) if (isSitemapRoute(list[i]!, files)) list.splice(i, 1)
const i18n = (nuxt.options as { i18n?: unknown }).i18n
const { routes, skipped } = seoSitemapPages({ htmlSitemap, pagination, pages: list, i18n, files })
for (const skip of skipped) logger.info(sitemapSkipMessage(skip))
list.push(...(routes as unknown as RoutePage[]))
})
})
}

94
lib/sitemapPages.ts Normal file
View File

@@ -0,0 +1,94 @@
// The HTML sitemap pages the layer registers (D-34, P33-68): one overview
// at seo.htmlSitemap.paths[locale], one group page at <path>/:group and, in
// the path pagination form, <path>/:group/<segment>/:page with the locale's
// segment. The module (lib/seo-module.ts) calls this from a pages:resolved
// hook that runs after @nuxtjs/i18n has localised the app's routes, so
// i18n never copies these routes into other locales (L4 WR-05): with i18n
// (any strategy but no_prefix) each route is named
// <name><routesNameSeparator><locale>, the name i18n reads the route's
// locale from, and exists once, at the configured path. A path an app page
// already has is the app's ('taken'); a path an app catch-all page covers
// ('[...slug].vue' at the root, or under a prefix) stays the catch-all's
// unless overCatchAll is true (L4 WR-04), because a static route would win
// over it in vue-router and shadow the CMS page there. Pure TypeScript, so
// `node --test` drives it.
import { flattenPages, pagePattern, patternCovers } from './guard.ts'
import type { SeoHtmlSitemapOption, SeoPaginationOption } from './options.ts'
import type { RoutePage } from './routes.ts'
/** Every route the layer adds starts with this name. */
export const SITEMAP_PAGE_PREFIX = 'seo-sitemap-'
export interface SitemapPagesInput {
htmlSitemap: SeoHtmlSitemapOption
pagination: SeoPaginationOption
/** The resolved pages (after @nuxtjs/i18n), the layer's own routes left out. */
pages: readonly RoutePage[]
/** nuxt.options.i18n when the app configures @nuxtjs/i18n. */
i18n?: unknown
/** The overview and group page components. */
files: { overview: string; group: string }
}
export interface SitemapRoute {
name: string
path: string
file: string
meta: { seoSitemap: { locale: string } }
}
export interface SitemapSkip {
locale: string
path: string
reason: 'taken' | 'catch-all'
}
/** True for a route the layer added (a former run of the hook). */
export const isSitemapRoute = (page: { name?: unknown; file?: unknown }, files: { overview: string; group: string }) =>
typeof page.name === 'string' && page.name.startsWith(SITEMAP_PAGE_PREFIX) && (page.file === files.overview || page.file === files.group)
/** The route-name suffix of a locale with @nuxtjs/i18n active, '' without. */
function localeSuffix(i18n: unknown, locale: string): string {
if (!i18n || typeof i18n !== 'object') return ''
const o = i18n as { strategy?: unknown; routesNameSeparator?: unknown }
if (o.strategy === 'no_prefix') return ''
const sep = typeof o.routesNameSeparator === 'string' && o.routesNameSeparator !== '' ? o.routesNameSeparator : '___'
return `${sep}${locale}`
}
/** The routes to add and the locales left out, with the reason. */
export function seoSitemapPages(input: SitemapPagesInput): { routes: SitemapRoute[]; skipped: SitemapSkip[] } {
const routes: SitemapRoute[] = []
const skipped: SitemapSkip[] = []
const html = input.htmlSitemap
if (html === false) return { routes, skipped }
const pages = flattenPages(input.pages).filter((p) => !isSitemapRoute(p as RoutePage, input.files))
const taken = new Set(pages.map((p) => p.fullPath))
const catchAlls = pages.map((p) => pagePattern(p.fullPath)).filter((p) => p.endsWith('/**'))
for (const [locale, path] of Object.entries(html.paths)) {
if (taken.has(path)) {
skipped.push({ locale, path, reason: 'taken' })
continue
}
if (!html.overCatchAll && catchAlls.some((pattern) => patternCovers(pattern, path))) {
skipped.push({ locale, path, reason: 'catch-all' })
continue
}
const suffix = localeSuffix(input.i18n, locale)
const meta = { seoSitemap: { locale } }
routes.push({ name: `${SITEMAP_PAGE_PREFIX}${locale}${suffix}`, path, file: input.files.overview, meta })
routes.push({ name: `${SITEMAP_PAGE_PREFIX}group-${locale}${suffix}`, path: `${path}/:group`, file: input.files.group, meta })
if (input.pagination.form === 'path') {
const segment = input.pagination.segments[locale] || input.pagination.param
routes.push({ name: `${SITEMAP_PAGE_PREFIX}group-page-${locale}${suffix}`, path: `${path}/:group/${segment}/:page(\\d+)`, file: input.files.group, meta })
}
}
return { routes, skipped }
}
/** The build log line of a skipped locale. */
export function sitemapSkipMessage(skip: SitemapSkip): string {
if (skip.reason === 'taken') return `HTML sitemap: the app has its own page at ${skip.path}; the layer's ${skip.locale} sitemap page is not registered`
return `HTML sitemap: ${skip.locale} ${skip.path} is rendered by the app's catch-all page; the layer's page is not registered (set seo.htmlSitemap.overCatchAll to serve it ahead of the catch-all)`
}