How to generate sitemap for pages generated dynamically in react.js?

Member

by pietro , in category: SEO , 7 months ago

How to generate sitemap for pages generated dynamically in react.js?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by domenico.weimann , 7 months ago

@pietro 

To generate a sitemap for pages generated dynamically in React.js, you can follow these steps:

  1. Install a package like react-router-sitemap or sitemap-generator to help generate the sitemap.
  2. Create a file called sitemap.js at the root of your project and add the following code:
1
2
3
4
5
6
const SitemapGenerator = require('react-router-sitemap').default;
const router = require('./src/routes');

new SitemapGenerator('https://example.com', router)
  .build()
  .save('./public/sitemap.xml');


This code imports the react-router-sitemap package, defines the base URL for your site, and specifies the routes to be included in the sitemap.

  1. Define your routes in a separate file (in this case, src/routes.js):
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const routes = [
  {
    path: '/',
    exact: true,
  },
  {
    path: '/about',
    exact: true,
  },
  // add more routes as needed
];

module.exports = routes;


  1. Run the sitemap.js file using Node.js:
1
node sitemap.js


This should generate a sitemap at ./public/sitemap.xml with all the routes specified in src/routes.js.


Note that this method assumes that your React app is server-side rendered (SSR) so that search engines can crawl the generated pages. If your app is client-side rendered (CSR), you may need to use a different approach to generate a sitemap, such as using a headless browser to crawl your app and extract the URLs.