Generate sitemap for static site with dynamic routes #12403
-
Hey all, I'm trying to build a sitemap for my static site generated by Next.js. I currently don't explicitly define a This functionality is really helpful because I have two dynamic routes that use When I run I've seen several tutorials/plugins on how to generate sitemaps for Next.js sites, like this, this, and this, but the solutions either:
Is there any way to hook into some API (private or public) that will let me just get all the pages in my site. I basically just want to programmatically generate the data seen in the screenshot above. Then, I can use that to generate my sitemap with a script post I would really appreciate any help or pointers here. Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 4 replies
-
Edit: Moved to docs #28346 |
Beta Was this translation helpful? Give feedback.
-
@helloworld // pages/sitemap.xml.js
const generateSitemap =(data, origin) => {
let xml = ''
data.pages.map(page => {
xml += `<url>
<loc>${origin + page.location}</loc>
<lastmod>${page.lastMod}</lastmod>
</url>`
})
return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${xml}
</urlset>`
}
export async function getServerSideProps({ res }) {
const data = /* do some async fetching here */
res.setHeader('Content-Type', 'text/xml')
res.write(generateSitemap(data, 'http://yoursite.com'))
res.end()
return {
props: {},
}
}
const SitemapIndex = () => null
export default SitemapIndex This will work perfectly for dynamic sitemaps 👍 |
Beta Was this translation helpful? Give feedback.
-
GENIUS! |
Beta Was this translation helpful? Give feedback.
-
We are adding official docs on sitemaps, please leave any feedback there! 🙏 |
Beta Was this translation helpful? Give feedback.
Edit: Moved to docs #28346