reactjs – How to add automatic sitemap code in React.js Website for Pharma Website?
Step 1 : – For static React (Create React App)
Use the sitemap or react-router-sitemap package.
install : npm install react-router-sitemap and create Create sitemap-generator.js
const Sitemap = require('react-router-sitemap').default;
function generateSitemap() {
return new Sitemap('https://www.orangebiotech.com')
.applyRoutes(require('./src/routes').default)
.build('public/sitemap.xml');
}
generateSitemap();
Run it in package.json :-
"scripts": {
"sitemap": "node sitemap-generator.js"
}
then Run :
npm run sitemap
Step 2: For dynamic pages (Node/Express backend)
Install : npm install sitemap
import express from "express";
import { SitemapStream, streamToPromise } from "sitemap";
const app = express();
app.get("/sitemap.xml", async (req, res) => {
const smStream = new SitemapStream({ hostname: "https://www.orangebiotech.com" });
smStream.write({ url: "/", changefreq: "daily", priority: 1.0 });
smStream.write({ url: "/about", changefreq: "monthly" });
const products = await getAllProducts();
products.forEach((p) => smStream.write({ url: `/product/${p.slug}`, changefreq: "weekly" }));
smStream.end();
const sitemap = await streamToPromise(smStream);
res.header("Content-Type", "application/xml");
res.send(sitemap.toString());
});
app.listen(3000);
Read more here: Source link
