toti
toti

Reputation: 43

How can I properly set dynamic sitemap.xml routes within a Vue Nuxt application?

I'm using @nuxtjs/sitemap to auto generate a sitemap in my Nuxt application, but it doesn't generate inner routes well, and I want to dynamically define routes of user posts, based on posts that actually exist. Consider this:

Instead of providing the 0,1 and 3 values in my sitemap I want to be able to auto-generate them and update the sitemap.

I can't seem to invoke nuxt's axios plugin from the nuxt.config.js file, and I don't understand how to accomplish this task, would love any guidance.

Upvotes: 1

Views: 3768

Answers (1)

Nicolas Pennec
Nicolas Pennec

Reputation: 7631

You cannot use the @nuxtjs/axios from the nuxt.config.js script, as explain here: https://github.com/nuxt-community/axios-module/issues/242#issuecomment-544923463

So you have to use directly axios to make your XHR call and generate the dynamic routes for your sitemap config as follows:

const axios = require('axios');

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

See example in docs: https://sitemap.nuxtjs.org/usage/sitemap-options#from-a-function-which-returns-a-promise

On each call to your https://example.com/sitemap.xml, the sitemap-module will execute the "route" function and update dynamically your sitemap.xml file.

Upvotes: 2

Related Questions