benoitdemaegdt / nuxt3-sitemap

sitemap generation for nuxt3
55 stars 6 forks source link

Sitemap generated is cached version, not current version for sitemap-dynamic #9

Closed jeffreytung7 closed 1 year ago

jeffreytung7 commented 2 years ago

In reference to sitemap-dynamic.ts, it appears that nuxt.options.nitro.publicAssets.push() runs before createSitemapFile().

So what happens is if it's the very first time running it, no sitemap.xml is generated in .output/public, but it is generated in node_modules/.cache/.sitemap/sitemap.xml

You can test this by deleting the .cache folder in node_modules, then npm run generate, and there will be no sitemap.xml in .output/public.

If it's the 2nd time running it and the .cache/.sitemap/sitemap.xml already exists, then it will generate a sitemap.xml in .output/public, but it is a copy of the old cached sitemap.xml.

I tried moving nuxt.options.nitro.publicAssets.push() to be below createSitemapFile(), but could not get it to work.

Is there some way to make it so that createSitemapFile is run before the cache sitemap.xml is copied into the public sitemap.xml?

This is preventing me from deploying it to Cloudflare Pages, since each time it builds it is a fresh install so no existing .cache folder.

benoitdemaegdt commented 2 years ago

Hey @jeffreytung7 👋

Sorry for late answer. There is indeed an issue I hadn't noticed so far. Thank you for raising this issue !

Unfortunately I couldn't find a way to solve this because of my limited understanding of Nuxt internal behavior. However, there is another way to generate a sitemap.xml that is simpler and easier to understand. I added some documentation about it in the README.md. This should solve all your cache issues 👌

Feel free to tell me if this works for your project 👍

jeffreytung7 commented 2 years ago

@benoitdemaegdt thanks for the reply! My project does not use nuxt/content, instead it fires a hook in nuxt.config to my database to get a list of slugs and adds it to nitro prerender. Do you know of a way to generate a sitemap with this?

benoitdemaegdt commented 2 years ago

I guess you can add a function here to get all slugs from your db.

export default defineEventHandler(async (event) => {
  const sitemap = new SitemapStream({ hostname: BASE_URL })

  const slugs = await getSlugsFromDB() // your own code in this function
  for (const slug of slugs) {
    sitemap.write({ url: slug, changefreq: 'monthly' })
  }

  const staticEndpoints = getStaticEndpoints()
  for (const staticEndpoint of staticEndpoints) {
    sitemap.write({ url: staticEndpoint, changefreq: 'monthly' })
  }

  sitemap.end()
  return streamToPromise(sitemap)
})

Hopefully this should work 🤞

jeffreytung7 commented 1 year ago

Awesome, it does work!