How to generate sitemap in React.js, how to create sitemap in React.js, and how to add sitemap in React.js are questions that usually come up when developers want search engines to discover the important URLs of a React website. The implementation, however, depends on how the application is built. A traditional React SPA does not automatically generate a complete XML sitemap, so you generally need to identify the site’s canonical routes and generate the sitemap during the build or deployment process. If the project uses Next.js, the approach is different because Next.js provides its own sitemap functionality.
This guide focuses specifically on the technical implementation of XML sitemaps for React websites. It covers traditional client-side React applications, React Router, dynamic routes, CMS-driven websites, Next.js, build-time generation, deployment, validation, troubleshooting, and Google Search Console submission.
How to Generate a Sitemap in React.js: The Short Answer
For a standard React SPA, the recommended approach is to generate the sitemap outside the browser using a Node.js script during the build or deployment process.
A typical implementation works like this:
- Identify the public, canonical routes.
- Exclude private and non-indexable URLs.
- Add dynamic URLs from your CMS, API, or database if necessary.
- Generate an XML sitemap with a maintained Node.js package.
- Save the file as sitemap.xml in the production build output.
- Deploy the file so it is accessible at /sitemap.xml.
- Validate the final production URL.
- Submit the sitemap through Google Search Console.
For example, if your React website uses the domain https://example.com, the final sitemap should normally be available at:
https://example.com/sitemap.xml
The important point is that React does not need to generate this XML inside the browser. Sitemap generation is better handled as part of your development and deployment workflow.
How to Create Sitemap in React.js: Why React Does Not Automatically Generate One
React is responsible for building user interfaces. It does not automatically maintain a complete list of every URL that should be included in a search engine sitemap.
A React project might have routes such as:
- /about
- /services
- /blog
- /contact
But the application could also contain routes such as:
- /login
- /account
- /checkout
- /dashboard
- /search
Not every one of these URLs belongs in an XML sitemap.
This is why the developer needs to define which routes are public and indexable. The sitemap should represent the website’s intended canonical URL structure rather than every route that happens to exist in the application.
For a small application, this could be as simple as:
const routes = [
“/”,
“/about”,
“/services”,
“/blog”,
“/contact”
];
For a larger application, the route inventory may come from multiple sources, including React Router configuration, a CMS, an API, or a database.
How to Generate Sitemap in React.js: Build-Time Generation Is Usually Better
A common mistake is attempting to generate the sitemap from a React component.
For example, creating a page called: /sitemap
and generating XML using JavaScript in the browser is not the ideal approach.
A sitemap is a machine-readable XML resource intended for crawlers. It should be available directly from the server or static hosting environment without depending on client-side JavaScript execution.
A better architecture is:
- React routes
- CMS/API data
- Node.js sitemap script
- sitemap.xml
- Production server
This means the sitemap is generated before deployment rather than after a user or crawler opens the website.
For static React applications, build-time generation is particularly convenient because the sitemap becomes part of the final deployment package.
How to Create Sitemap in React.js Using the sitemap Package
For a traditional React application, one practical option is the maintained sitemap npm package.
Install it with: npm install sitemap
The package provides APIs such as SitemapStream and streamToPromise for programmatic sitemap generation. Its current npm documentation supports generating a sitemap from JavaScript or Node.js code rather than relying on browser-side rendering.
Once installed, create a directory such as:
- scripts/
- generate-sitemap.mjs
Then add a generation script:
- import { SitemapStream, streamToPromise } from “sitemap”;
- import { Readable } from “node:stream”;
- import { mkdir, writeFile } from “node:fs/promises”;
- import path from “node:path”;
const hostname = process.env.SITE_URL;
if (!hostname) {
throw new Error(“SITE_URL is required”);
}
const routes = [
“/”,
“/about”,
“/services”,
“/blog”,
“/contact”
];
const links = routes.map((url) => ({
url
}));
const sitemap = new SitemapStream({
hostname
});
const xml = await streamToPromise(
Readable.from(links).pipe(sitemap)
);
const outputDirectory = path.resolve(“dist”);
const outputFile = path.join(
outputDirectory,
“sitemap.xml”
);
await mkdir(outputDirectory, {
recursive: true
});
await writeFile(
outputFile,
xml.toString(),
“utf8”
);
console.log(`Sitemap generated at ${outputFile}`);
The important part is that the script receives the canonical domain from an environment variable rather than hard-coding a development URL.
How to Generate Sitemap in React.js During the Build
Once the generation script is ready, connect it to your build command.
For example, a Vite-based React project might use:
{
“scripts”: {
“build”: “vite build && node scripts/generate-sitemap.mjs”
}
}
Running: npm run build
will first create the React production build and then generate: dist/sitemap.xml
The resulting build directory could look like:
- dist/
- assets/
- index.html
- robots.txt
- sitemap.xml
Your hosting provider then needs to publish the contents of dist.
This method is particularly useful when the site’s routes do not change frequently. Whenever new indexable routes are introduced, the build can regenerate the sitemap automatically.
How to Create Sitemap in React.js from React Router Routes
React Router and an XML sitemap have different purposes.
React Router determines which React component should be displayed for a particular URL. A sitemap, on the other hand, tells search engines which URLs are worth discovering.
You can maintain a separate list of sitemap-eligible routes:
export const sitemapRoutes = [
{
path: “/”,
indexable: true
},
{
path: “/about”,
indexable: true
},
{
path: “/services”,
indexable: true
},
{
path: “/login”,
indexable: false
},
{
path: “/dashboard”,
indexable: false
}
];
Then filter the routes before generating the XML:
const routes = sitemapRoutes
.filter((route) => route.indexable)
.map((route) => route.path);
This approach is safer than automatically adding every route from your application.
It also makes future maintenance easier because developers can immediately see which routes are intended to be included in the sitemap.
React Routes and Sitemap URLs: Which URLs Should Be Included?
The sitemap should contain URLs that are publicly accessible and that you want search engines to discover.
For most React websites, these can include:
- Homepage
- Main service pages
- Product pages
- Published blog posts
- Public category pages
- Important location pages
- Public landing pages
- Other canonical pages intended for organic search
Routes that generally should not be included include:
- Login pages
- Account areas
- Checkout pages
- Admin dashboards
- Internal search pages
- Temporary URLs
- Tracking URLs
- Session-based URLs
- Duplicate URLs
- Pages intentionally marked noindex
For example, if your React application supports:
/products/laptop
/products/laptop?utm_source=facebook
/products/laptop/
you should normally select one canonical URL rather than adding all three variations.
How to Generate Sitemap in React.js Without Duplicate URLs
Duplicate URLs can appear easily when a React application supports multiple URL formats.
Trailing slashes are one example:
- /products/laptop
- /products/laptop/
Query parameters are another:
/products/laptop?source=home
/products/laptop?campaign=sale
The sitemap should generally contain the canonical version: https://example.com/products/laptop
You can normalize routes before passing them to the sitemap generator:
function normalizePath(path) {
if (path === “/”) {
return “/”;
}
return path.replace(/\/+$/, “”);
}
const uniqueRoutes = [
…new Set(routes.map(normalizePath))
];
This simple step can prevent multiple variations of the same page from entering the XML file.
How to Create Sitemap in React.js for Dynamic Routes
Dynamic routes require more than a static route list.
Consider an application with: /products/:slug
The React router may use one route definition, but the actual website could have hundreds of URLs:
- /products/iphone-17
- /products/samsung-galaxy
- /products/macbook-air
The sitemap generator needs the actual URLs.
If product data comes from an API, for example:
const products = [
{
slug: “iphone-17”,
published: true
},
{
slug: “samsung-galaxy”,
published: true
},
{
slug: “draft-product”,
published: false
}
];
you can create the sitemap URLs with:
const productUrls = products
.filter((product) => product.published)
.map(
(product) => `/products/${product.slug}`
);
The same principle applies to blog articles, categories, services, locations, and other CMS-driven pages.
How to Generate Sitemap in React.js from a CMS or API
If your React website receives content from a CMS, the sitemap should ideally use that same source to discover dynamic URLs.
For example, a CMS might return:
[
{
slug: “react-seo-guide”,
status: “published”,
indexable: true
},
{
slug: “draft-guide”,
status: “draft”,
indexable: false
}
]
You can filter the data before creating sitemap entries:
const blogUrls = posts
.filter(
(post) =>
post.status === “published” &&
post.indexable === true
)
.map(
(post) => `/blog/${post.slug}`
);
This is more reliable than maintaining hundreds of URLs manually.
For a React website with frequently updated content, the sitemap generation process can be triggered by a deployment, CMS webhook, scheduled task, or server-side process.

SEO Services for React Sitemap Implementation
A React sitemap can become part of a much broader technical SEO workflow when a website has complex routing, dynamic content, multiple environments, or hundreds of indexable URLs. Professional SEO Services can help developers and marketing teams connect sitemap generation with canonical URLs, crawlability, internal linking, and indexability rather than managing the XML file separately.
How to Add Sitemap in React.js: Where Should sitemap.xml Be Served?
Creating the XML file is only half of the implementation.
You also need to make sure that crawlers can access it.
For most websites, the recommended URL is: https://example.com/sitemap.xml
If your React project produces: dist/sitemap.xml
your hosting environment should serve that file from the website root.
When someone requests: https://example.com/sitemap.xml
the server should return the XML document.
It should not return the React application’s index.html.
This distinction is particularly important for single-page applications because hosting configurations often redirect unknown paths to index.html to support client-side routing.
How to Add Sitemap in React.js to the Public Directory
If your React website is small and has mostly static routes, you can manually place the sitemap inside the public directory:
- public/
- robots.txt
- sitemap.xml
- favicon.icon
Depending on your build tool, files inside public are copied to the production build.
This makes: public/sitemap.xml
available as: https://example.com/sitemap.xml
However, manually maintaining this file becomes less practical as the number of pages increases.
If your website contains hundreds or thousands of dynamic URLs, automated generation is usually the better solution.
How to Add Sitemap in React.js: Generating vs Serving the File
These two steps should not be confused.
| Task |
What it means |
| Generate sitemap |
Create valid XML containing your URLs |
| Save sitemap |
Write the XML to a file or server response |
| Deploy sitemap |
Make the generated file part of production |
| Serve sitemap |
Make /sitemap.xml publicly accessible |
| Submit sitemap |
Tell Google where the sitemap exists |
A developer can successfully generate sitemap.xml locally and still have a broken production sitemap if the file is not included in the deployment.
Always test the final production URL.
React Sitemap Validation: What to Check Before Deployment
Before submitting a sitemap, verify the XML itself and the URLs inside it.
Check the following:
- The XML is well-formed.
- The file uses UTF-8.
- URLs are absolute.
- URLs use the production domain.
- URLs use HTTPS when HTTPS is the canonical protocol.
- URLs do not contain accidental tracking parameters.
- Private pages are excluded.
- Duplicate URLs are removed.
- The sitemap is publicly accessible.
- The sitemap does not contain staging or localhost URLs.
A valid entry should look similar to:
<url>
<loc>https://example.com/about</loc>
</url>
An entry such as this should never appear in a production sitemap:
<url>
<loc>http://localhost:5173/about</loc>
</url>
Google’s sitemap documentation specifies that sitemap URLs should be absolute URLs and that XML sitemap files should use UTF-8 encoding.
How to Generate Sitemap in React.js Without Localhost URLs
One of the easiest mistakes to make during development is using the local development address when generating URLs.
For example: http://localhost:3000
may work perfectly during testing but is obviously useless in a production sitemap.
Instead, define the production domain through an environment variable: SITE_URL=https://example.com
Then:
const hostname = process.env.SITE_URL;
if (!hostname) {
throw new Error(
“SITE_URL environment variable is missing”
);
}
You can also enforce HTTPS:
if (!hostname.startsWith(“https://”)) {
throw new Error(
“SITE_URL must use HTTPS”
);
}
This is particularly useful in CI/CD pipelines because it prevents a deployment from silently producing incorrect URLs.
Generative Engine Optimization for React Websites
Generative Engine Optimization is increasingly relevant to websites that want their content to be understandable and discoverable across modern search experiences and AI-driven systems. While an XML sitemap does not directly guarantee visibility in generative results, a clear URL structure, accessible content, consistent canonical signals, and technically sound site architecture provide a stronger foundation.
How to Generate Sitemap in React.js for Dynamic Websites
Dynamic websites require a plan for keeping the sitemap synchronized with the URL inventory.
Suppose a React e-commerce website adds new products every day. A sitemap generated once several months ago will eventually become outdated.
There are several practical options.
Build-Time Regeneration
If content changes are tied to application deployments, regenerate the sitemap every time the website is built.
This is straightforward and works well for many marketing websites and smaller content platforms.
Scheduled Regeneration
If content changes independently from application releases, a scheduled job can regenerate the sitemap.
For example, a scheduled process can:
- Fetch published content.
- Filter indexable records.
- Generate the XML.
- Validate the XML.
- Publish the updated sitemap.
CMS Webhooks
A CMS can trigger a sitemap generation process whenever content is published or removed.
This can be useful for websites with frequently changing blog posts, products, or landing pages.
Server-Side Generation
For applications with very large or frequently changing URL inventories, the sitemap can be generated dynamically on the server.
The sitemap npm package also provides server-side generation patterns, including streaming sitemap responses.
The correct option depends on how frequently your URLs change and how your application is hosted.
How to Create Sitemap in React.js for Next.js Applications
Next.js requires a separate explanation because it is not simply another name for a React SPA.
Next.js is a React framework that provides its own routing, rendering, metadata, and application-level functionality.
If your application uses the Next.js App Router, Next.js provides a native sitemap convention.
A typical structure can include:
- app/
- layout.js
- page.js
- sitemap.js
A basic sitemap implementation can look like:
export default function sitemap() {
return [
{
url: “https://example.com”,
lastModified: new Date()
},
{
url: “https://example.com/about”,
lastModified: new Date()
}
];
}
The exact implementation should follow the Next.js version and routing architecture used by the project.
The key takeaway is that you should not automatically apply a generic React SPA sitemap strategy to a Next.js project. Next.js has framework-level capabilities that can make sitemap generation more integrated with the application.

How to Generate Sitemap in React.js: React SPA vs SSR and SSG
The implementation changes significantly depending on how the React application is rendered.
| Application type |
Sitemap generation |
Best approach |
Sitemap location |
Main consideration |
| Traditional React SPA |
Build-time Node.js script |
Generate from route configuration |
/sitemap.xml |
Maintain canonical routes |
| React SPA + CMS |
Build-time CMS/API generation |
Generate from published content |
/sitemap.xml |
Keep CMS data synchronized |
| React + Vite |
Build script |
Generate after production build |
/sitemap.xml |
Avoid browser-side XML generation |
| Next.js App Router |
Native sitemap functionality |
Use Next.js conventions |
/sitemap.xml |
Follow framework implementation |
| React SSR application |
Server-side generation |
Generate from live data |
/sitemap.xml |
Caching and performance |
| Static React website |
Static generation |
Generate during deployment |
/sitemap.xml |
Regenerate when routes change |
This distinction is important because the sitemap strategy should follow the application’s rendering and data architecture.
How to Add Sitemap in React.js with robots.txt
You can also reference the sitemap from your robots.txt file.
A basic example is: User-agent: * Allow: /
Sitemap: https://example.com/sitemap.xml
The sitemap URL should be absolute.
After deployment, test both: https://example.com/robots.txt
and: https://example.com/sitemap.xml
The robots.txt file can help crawlers discover the sitemap, but it does not replace the requirement to serve the XML correctly.
How to Generate Sitemap in React.js: Managing Large Websites
Large React websites may eventually exceed the limits of a single sitemap.
Google currently documents a limit of 50,000 URLs or 50 MB uncompressed for an individual sitemap.
If your website exceeds those limits, split the URLs into multiple sitemap files.
For example:
- sitemap-products.xml
- sitemap-blog.xml
- sitemap-categories.xml
Then use a sitemap index to reference them.
This can also make large websites easier to manage because different content types can be generated independently.
For example:
| Sitemap |
Content |
| sitemap-products.xml |
Product URLs |
| sitemap-blog.xml |
Blog articles |
| sitemap-categories.xml |
Category pages |
| sitemap-services.xml |
Service pages |
The exact structure should reflect your site’s URL architecture and publishing workflow.
React Sitemap Troubleshooting: Common Problems and Solutions
| Problem |
Possible cause |
Recommended solution |
| /sitemap.xml returns 404 |
File was not deployed |
Check the final build directory |
| Sitemap returns index.html |
SPA fallback is intercepting the request |
Configure static file handling |
| Localhost URLs appear |
Wrong environment variable |
Set the production SITE_URL |
| Staging URLs appear |
Staging configuration reached production |
Check deployment variables |
| HTTP URLs appear |
Incorrect domain configuration |
Use the canonical HTTPS domain |
| Duplicate URLs appear |
Multiple route formats |
Normalize and deduplicate routes |
| /page and /page/ both appear |
Slash inconsistency |
Use one canonical format |
| Query parameters appear |
URLs were collected without filtering |
Remove tracking and unnecessary parameters |
| Private routes appear |
All application routes were included |
Add an indexability filter |
| Dynamic pages are missing |
Generator only knows static routes |
Fetch CMS/API/database URLs |
| XML is malformed |
Incorrect manual generation |
Use a sitemap library and validate output |
| Sitemap is outdated |
Generation only happened once |
Automate regeneration |
| Sitemap is too large |
URL count or file size exceeded |
Split into multiple sitemap files |
How to Create Sitemap in React.js: Handling Environment Variables
Environment variables deserve special attention because they can affect every URL in the sitemap.
A simple implementation might use: const hostname = process.env.SITE_URL;
Development: SITE_URL=http://localhost:3000
Production: SITE_URL=https://example.com
The problem occurs when the development value is accidentally used during a production build.
For that reason, production deployments should explicitly define the correct environment variables.
It is also useful to validate the hostname before generating the sitemap: const hostname = process.env.SITE_URL;
if (!hostname) {
throw new Error(“SITE_URL is required”);
}
if (!hostname.startsWith(“https://”)) {
throw new Error(
“SITE_URL must start with https://”
);
}
A failed build is much better than successfully deploying a sitemap containing the wrong domain.
local SEO agency Support for React Websites in Egypt
For Egyptian businesses targeting cities and service areas, a local SEO agency can help identify which location-specific React pages should actually be indexable and represented in the sitemap. The technical implementation should then generate only the canonical versions of those pages rather than creating duplicate city or parameter-based URLs.
React Sitemap Validation: Final Production Checklist
Before publishing a React sitemap, use this checklist.
Routes
- Important public URLs are included.
- Dynamic URLs are generated from reliable data.
- Private routes are excluded.
- Duplicate URLs are removed.
- Tracking parameters are excluded.
- Trailing-slash rules are consistent.
- Canonical URLs are used.
XML
- XML is valid.
- UTF-8 encoding is used.
- URLs are absolute.
- The correct XML sitemap namespace is present.
- The file is not unnecessarily oversized.
Production
- SITE_URL points to the production domain.
- URLs use HTTPS where appropriate.
- No localhost URLs exist.
- No staging URLs exist.
- /sitemap.xml returns XML.
- /sitemap.xml does not return index.html.
- The sitemap does not require authentication.
Search engines
- Sitemap is referenced in robots.txt if appropriate.
- Sitemap is submitted in Google Search Console.
- Search Console is monitored for sitemap errors.
How to Submit a React Sitemap to Google Search Console
Once the sitemap is live, submitting it to Google Search Console is straightforward.
First, make sure the production URL works:
https://example.com/sitemap.xml
Then:
- Open Google Search Console.
- Select the verified website property.
- Open the Sitemaps section.
- Enter the sitemap path.
- Submit the sitemap.
- Review the status and any reported errors.
For example, you can submit: sitemap.xml
You can also reference the complete sitemap URL in robots.txt.
It is important to remember that submitting a sitemap is a discovery signal, not a guarantee that Google will crawl or index every URL included in the file.
How to Generate Sitemap in React.js: Best-Practice Workflow
For a traditional React SPA, a practical production workflow looks like this:
- Define the application’s canonical public routes.
- Identify dynamic URLs from your CMS, API, or database.
- Remove private and non-indexable URLs.
- Normalize URL formats.
- Remove duplicates.
- Generate the XML during the build or deployment process.
- Save the file to the production build.
- Deploy the file to the website root.
- Open /sitemap.xml in a browser to verify it.
- Check the XML for production URLs.
- Reference it in robots.txt.
- Submit it through Google Search Console.
For websites with frequently changing content, automate the generation process rather than relying on manual updates.
The exact implementation should always be tested against the current React, Node.js, build-tool, and hosting environment before being deployed to production.
Modern website design and React Technical Structure
Modern website design should consider more than the appearance of the interface. A React website also needs a logical route structure, accessible pages, consistent URLs, appropriate rendering, and a deployment setup that allows important resources such as sitemap.xml and robots.txt to be accessed directly. Good visual design and sound technical architecture should work together.
FAQ: How to Generate, Create, and Add a Sitemap in React.js
How do I create a sitemap in React.js?
To create a sitemap in React.js, identify the public canonical routes that should be discovered by search engines and generate an XML file from them. For a standard React SPA, a Node.js build script using a maintained sitemap package is a practical approach. Dynamic URLs can be obtained from a CMS, API, or database.
How do I generate sitemap.xml?
You can generate sitemap.xml programmatically with the sitemap npm package. Define your URLs, pass them to SitemapStream, convert the generated stream to XML, and write the file to your production build directory.
For a static React website, this process can run automatically as part of the production build.
Where should sitemap.xml be placed?
The sitemap should normally be publicly accessible at the root of your website: https://example.com/sitemap.xml
For many React projects, the generated file can be placed in the production build directory so the hosting platform serves it from the domain root.
Can React generate a sitemap automatically?
React itself does not automatically generate a complete XML sitemap. A traditional React SPA normally requires a separate generation process, such as a Node.js build script, deployment task, or server-side endpoint.
If the application uses Next.js, use Next.js’s native sitemap capabilities instead of treating it as a basic React SPA.
How do I handle dynamic routes?
Dynamic routes should be generated from the actual URLs stored in your CMS, API, or database.
For example:
const urls = products
.filter((product) => product.published)
.map(
(product) => `/products/${product.slug}`
);
Only published and indexable URLs should be added. How do I submit a React sitemap to Google?
Make sure the sitemap is publicly accessible at /sitemap.xml, then submit the sitemap through Google Search Console’s Sitemaps section. You can also reference the sitemap from robots.txt.
Does a React sitemap guarantee indexing?
No. A sitemap helps search engines discover URLs, but it does not guarantee crawling or indexing.
A sitemap cannot fix problems with rendering, canonicalization, blocked resources, poor internal linking, duplicate content, or low-quality pages. Those technical and content issues need to be addressed separately.
How often should a React sitemap be updated?
The sitemap should be updated whenever the set of important indexable URLs changes. For static websites, rebuilding the sitemap during deployment may be sufficient. For websites with frequently changing products, articles, categories, or other content, consider automated regeneration through CMS webhooks, scheduled jobs, or server-side generation.
How to Generate a Sitemap in React.js Correctly
The right way to approach a React sitemap depends on the application’s architecture.
For a traditional React SPA, the most practical solution is usually to maintain a clear list of canonical routes and generate sitemap.xml during the build or deployment process. Dynamic websites should retrieve their URLs from the CMS, API, or database, while private, duplicate, parameterized, and non-indexable URLs should be filtered out.
The generated file then needs to be deployed and served from: https://example.com/sitemap.xml
Next.js applications are different because Next.js provides native sitemap functionality, so developers should follow the framework’s conventions rather than applying a generic SPA solution.
Most importantly, generating a sitemap is only one part of technical SEO. The React application’s rendering, routing, canonical URLs, internal linking, HTTP responses, and content accessibility all need to work correctly as well.
Need help implementing a technically sound sitemap for a React website? Contact Be One for technical SEO and development support to make sure your React application is properly structured for search engines.