diff --git a/README.md b/README.md index 6b9bdd6..d559425 100644 --- a/README.md +++ b/README.md @@ -357,6 +357,8 @@ export const handle: SitemapHandle = { } ``` +This applies to all routes, including `root.tsx`. The `root.tsx` sitemap function acts as a fallback and will run for any route that does not define its own sitemap handle. + ### Handling sitemap index + dynamic sitemaps + robots.txt If you want to generate different sitemaps based on the language you can use the following approach: diff --git a/src/remix/sitemap.ts b/src/remix/sitemap.ts index 33a4281..ce2695b 100644 --- a/src/remix/sitemap.ts +++ b/src/remix/sitemap.ts @@ -42,6 +42,11 @@ const createExtendedRoutes = (routes: RouteManifest } => { + return Boolean(handle && typeof handle === "object" && "sitemap" in handle && typeof handle.sitemap === "function") +} + const generateRemixSitemapRoutes = async ({ domain, sitemapData, @@ -54,21 +59,32 @@ const generateRemixSitemapRoutes = async ({ // Add the url to each route const extendedRoutes = createExtendedRoutes(routes) + const rootRoute = extendedRoutes.find(({ id }) => id === "root") + const rootHandle = rootRoute?.module?.handle + + const hasRootHandle = hasSitemapHandle(rootHandle) + const transformedRoutes = await Promise.all( extendedRoutes.map(async (route) => { - const url = route.url // We don't want to include the root route in the sitemap if (route.id === "root") return - // If the route has a module, get the handle + + const url = route.url const handle = route.module?.handle - // If the route has a sitemap function, call it and return the sitemap entries - if (handle && typeof handle === "object" && "sitemap" in handle && typeof handle.sitemap === "function") { - // Type the function just in case - const sitemap = handle.sitemap as SitemapFunction - const sitemapEntries: SitemapFunctionReturnData = await sitemap(domain, url, sitemapData) + + // Run the route sitemap function if it exists + if (hasSitemapHandle(handle)) { + const sitemapEntries = await handle.sitemap(domain, url, sitemapData) + return { url, sitemapEntries, id: route.id } + } + + // As a fallback run the root route sitemap function + if (hasRootHandle) { + const sitemapEntries = await rootHandle.sitemap(domain, url, sitemapData) return { url, sitemapEntries, id: route.id } } - // Otherwise, just return the route as a single entry + + // If no sitemap function was found, just return the route as a single entry return { url, sitemapEntries: null, id: route.id } }) )