Dynamically generate sitemap using @nuxtjs/sitemap
Asked Answered
T

1

3

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?

Teresaterese answered 24/6, 2021 at 11:35 Comment(0)
N
3

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

Noble answered 24/6, 2021 at 13:23 Comment(3)
Mr.kissu I think I figured it out. It happened because I stupidly set default: { lastmod: new Date() }, in my case I should wrap lastmod into axios callTeresaterese
e.g., return data.map((post) => ({ url: /posts/${post.id}, lastmod: new Date(), }))Teresaterese
Thank a lot, the yarn generate, instead of yarn build was crucial for me.Stupor

© 2022 - 2024 — McMap. All rights reserved.