skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    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]
    }
    
    

  2. This is how I am doing it in file sitemap.js.

    import { getPostsForSitemap } from "../service";
    
    const URL = "https://example.com";
    
    export default async function sitemap() {
      const data = await getPostsForSitemap();
      const posts = data.data.map((post) => ({
        url: `${URL}/${post.attributes.slug}`,
        lastModified: post.attributes.updatedAt,
      }));
    
      const routes = ["/", "/about", "/contact"].map((route) => ({
        url: `${URL}${route}`,
        lastModified: new Date().toISOString(),
      }));
    
      return [...posts, ...routes];
    }
    

    Please note that my api (strapi) returns list of posts with slug and last updated date.
    I am doing data fetching in function getPostsForSitemap.
    Here is sitemap generated using this code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search