Search code examples
vue.jsnuxt.jssitemap

Dynamically generate sitemap using @nuxtjs/sitemap


I am using @nuxtjs/sitemap as my sitemap generator, some of the routes are given by ajax.

I need it to have latest api data whenever someone visit /sitemap.xml, is it possible to do it with this library?

My config here in nuxt.config.js:

{
  sitemap: {
    defaults: {
      lastmod: new Date(),
    },
    routes: async () => {
      const { data } = await axios.get(
        'https://jsonplaceholder.typicode.com/posts'
      )
      return data.map((post) => `/posts/${post.id}`)
    },

    cacheTime: 1,
  },
}

When I activate my server and visit /sitemap.xml,

it shows the latest routes with correct lastmod,

but after that it won't update again,

how can I do that?


Solution

  • Your setup looks fine and this is working great so far, the thing is that the sitemap is probably created during build time. So, if:

    • target: static >> yarn generate && yarn start
    • target: server (default) >> yarn build && yarn start

    This should work fine in real world scenario tho, because you'll push some fresh code to your hosting platform, and it will build your new app.
    Hence it'll create the new updated sitemap.


    It may also come from the fact that the default cacheTime is set to 15min. Maybe try to change this to something smaller.


    Is your website supposed to have dynamically moving parts without a new build, so like depending on a highly dynamic API or alike?
    If it's the case, maybe look for this Github issue: https://github.com/nuxt-community/sitemap-module/issues/186