reactjsnext.jssitemap

How to map through dynamic pages in Next13.3 to create sitemap


I am using the recommended way to create a sitemap in Next13.3+ using a sitemap.js file in the app folder with the following code (obviously changing these examples for the real urls)

export default function sitemap() {
    return [
        {
            url: 'https://acme.com',
            lastModified: new Date(),
        },
        {
            url: 'https://acme.com/about',
            lastModified: new Date(),
        },
        {
            url: 'https://acme.com/blog',
            lastModified: new Date(),
        },
    ]
}

However I would like to map over the dynamically created pages in a [slug] folder with a page.js in it to create the items in the sitemap.

How can I programmatically refer to those dynamic pages in the sitemap.js?

I have tried using $(slug) in an arrow function but this does not work.

const routes = ["", "/$(slug]"].map((route) => ({
  url: `${URL}${route}`,
  lastModified: new Date().toISOString(),
}));
return routes

Thanks for any advice


Solution

  • This is how I fixed it...

    import { getPages } from "../../sanity/sanity-utils"
    
    const URL = "https://example.com";
    
    export default async function sitemap() {
    
        const pages = await getPages();
    
        const routes = ["", "/*"].map((route) => ({
            url: `${URL}${route}`,
            lastModified: new Date().toISOString(),
        }));
    
        const pages1 = pages.map(({ slug }) => ({
            url: `${URL}/${slug}`,
            lastModified: new Date().toISOString(),
        }));
    
        return [...routes, ...pages1]
    }