Automatically Generate Sitemap in React Router v7

Y
Sun Jul 27 2025·32 min read

This post will go through the process of generating the Sitemap in React Router v7 from virtual:react-router/server-build

TL;DR: This is loader() for sitemap.xml route

import * as serverBuild from 'virtual:react-router/server-build'

export const loader = async ({ request }: LoaderFunctionArgs) => {
	const url = new URL(request.url)
	const origin = url.origin

	const systemSitemaps = sitemapUrlsFromServerBuild(origin, serverBuild.routes)
}

	const urlTags = toXmlUrlTagss([...systemSitemaps])

	try {
		return new Response(
			`<?xml version="1.0" encoding="UTF-8"?>
				<urlset
					xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
				>
					${urlTags.join('\n')}
				</urlset>`,
			{
				status: 200,
				headers: {
					'Content-Type': 'application/xml',
					'X-Content-Type-Options': 'nosniff',
					'Cache-Control': 'public, max-age=3600',
				},
			},
		)
	} catch (e) {
		console.error('Error generating sitemap:', e)
		throw new Response('', { status: 500 })
	}
}

/**
 * Generate sitemap URLs from server build routes
 */
function sitemapUrlsFromServerBuild(
	origin: string,
	routes: typeof serverBuild.routes,
): SitemapURL[] {
	const urls: SitemapURL[] = []
	const now = new Date()

	for (const key in routes) {
		/**
		 * 'routes/papa/dashboard/assets/resource': {
		 *   id: 'routes/papa/dashboard/assets/resource',
		 *   parentId: 'routes/papa/dashboard/layout/route',
		 *   path: 'assets/resource',
		 *   index: undefined,
		 *   caseSensitive: undefined,
		 *   module: [Object: null prototype] [Module] {
		 *     action: [Getter],
		 *     loader: [Getter]
		 *   }
		 * },
		 */
		const route = routes[key]
		if (!route || !route.path) continue
		const path = route.path

		if (
			!path.includes(':') && // exclude dynamic segments
			!path.includes('*') // exclude catch-all segments
		) {
			let parentRoute = route.parentId ? routes[route.parentId] : undefined
			let fullPath = path

			while (parentRoute) {
				if (parentRoute?.path) {
					fullPath = `${parentRoute.path}/${fullPath}`
				}
				parentRoute = parentRoute.parentId
					? routes[parentRoute.parentId]
					: undefined
			}

			// filter
			if (
				fullPath.startsWith('/dashboard') ||
				fullPath.startsWith('/api') ||
				['/sitemap.xml', '/robots.txt'].includes(fullPath)
			) {
				continue
			}

			urls.push({
				loc: `${origin}${fullPath}`,
				lastmod: now,
			})
		}
	}

	return urls
}

sitemapUrlsFromServerBuild() function will loop through the routes, concat current routes with all its parents, and returns SitemapUrl typed array.

/**
 * @see https://www.sitemaps.org/protocol.html#sitemapElement
 */
export interface SitemapURL {
	/** URL of the page. This URL must begin with the protocol (such as http) and end with a trailing slash, if your web server requires it. This value must be less than 2,048 characters. */
	loc: string
	/**
	 * The date of last modification of the page. This date should be in W3C Datetime format. This format allows you to omit the time portion, if desired, and use YYYY-MM-DD.
	 *
	 * Note that the date must be set to the date the linked page was last modified, not when the sitemap is generated.
	 *
	 * Note also that this tag is separate from the If-Modified-Since (304) header the server can return, and search engines may use the information from both sources differently.
	 * @see https://www.w3.org/TR/NOTE-datetime */
	lastmod?: Date
	/**
	 * How frequently the page is likely to change. This value provides general information to search engines and may not correlate exactly to how often they crawl the page. Valid values are:
	 *
	 * - always
	 * - hourly
	 * - daily
	 * - weekly
	 * - monthly
	 * - yearly
	 * - never
	 *
	 * The value "always" should be used to describe documents that change each time they are accessed. The value "never" should be used to describe archived URLs.
	 *
	 * Please note that the value of this tag is considered a hint and not a command. Even though search engine crawlers may consider this information when making decisions, they may crawl pages marked "hourly" less frequently than that, and they may crawl pages marked "yearly" more frequently than that. Crawlers may periodically crawl pages marked "never" so that they can handle unexpected changes to those pages.
	 */
	changefreq?:
		| 'always'
		| 'hourly'
		| 'daily'
		| 'weekly'
		| 'monthly'
		| 'yearly'
		| 'never'
	/**
	 * The priority of this URL relative to other URLs on your site. Valid values range from 0.0 to 1.0. This value does not affect how your pages are compared to pages on other sites—it only lets the search engines know which pages you deem most important for the crawlers.
	 *
	 * The default priority of a page is 0.5.
	 *
	 * Please note that the priority you assign to a page is not likely to influence the position of your URLs in a search engine's result pages. Search engines may use this information when selecting between URLs on the same site, so you can use this tag to increase the likelihood that your most important pages are present in a search index.
	 *
	 * Also, please note that assigning a high priority to all of the URLs on your site is not likely to help you. Since the priority is relative, it is only used to select between URLs on your site.
	 * @default 0.5
	 */
	priority?: number
}

The serverBuild.routes Looks Like This

{
  root: {
    id: 'root',
    parentId: undefined,
    path: '',
    index: undefined,
    caseSensitive: undefined,
    module: [Object: null prototype] [Module] {
      meta: [Getter],
      Layout: [Getter],
      loader: [Getter],
      default: [Getter],
      ErrorBoundary: [Getter]
    }
  },
  'routes/web/layout': {
    id: 'routes/web/layout',
    parentId: 'root',
    path: undefined,
    index: undefined,
    caseSensitive: undefined,
    module: [Object: null prototype] [Module] {
      meta: [Getter],
      default: [Getter],
      ErrorBoundary: [Getter]
    }
  },
  'routes/web/index/route': {
    id: 'routes/web/index/route',
    parentId: 'routes/web/layout',
    path: undefined,
    index: true,
    caseSensitive: undefined,
    module: [Object: null prototype] [Module] { default: [Getter] }
  },
  'routes/web/blog/post-slug/route': {
    id: 'routes/web/blog/post-slug/route',
    parentId: 'routes/web/blog/layout',
    path: ':postSlug',
    index: undefined,
    caseSensitive: undefined,
    module: [Object: null prototype] [Module] { default: [Getter] }
  },
  'routes/web/$/route': {
    id: 'routes/web/$/route',
    parentId: 'routes/web/layout',
    path: '/*',
    index: undefined,
    caseSensitive: undefined,
    module: [Object: null prototype] [Module] {
      loader: [Getter],
      default: [Getter]
    }
  },
  'routes/web/_robots.txt': {
    id: 'routes/web/_robots.txt',
    parentId: 'routes/web/layout',
    path: '/robots.txt',
    index: undefined,
    caseSensitive: undefined,
    module: [Object: null prototype] [Module] { loader: [Getter] }
  },

  • react-router
  • remix
  • sitemap

Subscribe to new posts!

If you like topics like Tech, Software Development, or Travel. Welcome to subscribe for free to get some fresh ideas!