Extending prerender routes with Sanity
I'm trying to extend prerender routes fallowing this example
export default defineNuxtConfig({
hooks: {
async 'nitro:config' (nitroConfig) {
if (nitroConfig.dev) { return }
// ..Async logic..
nitroConfig.prerender.routes.push('/custom')
}
}
})
At this point I believe Sanity Client is not initialized. I'm straggling to call Sanity and pass the array of dynamic routes who are not prerender by Nitro.
I installed @sanity/client and added the fallowing code to my nuxt.config created a function where I write my fetching logic and then calling it inside of hook
import sanityClient from '@sanity/client'
export const getRoutes = async () => {
const query = '*[_type == "article"].uid.current'
const client = sanityClient({
projectId: 'XXX',
dataset: 'production',
apiVersion: '2022-11-21',
useCdn: true,
})
const data = await client.fetch(query)
return data
}
export default defineNuxtConfig({
hooks: {
async 'nitro:config'(nitroConfig: any) {
if (nitroConfig.dev) { return }
const routes = await getRoutes()
nitroConfig.prerender.routes.push(...routes)
}
},
})
Like this everything works as desired and I get the wanted results with no errors. However I still have some small questions.
- I see that @sanity/client is used inside of @nuxtjs/sanity. Is there a way to make the call without adding @sanity/client as dependency to my project, using @nuxtjs/sanity only ?
- This question is not related to @nuxtjs/sanity, however what is the best way to move the whole fetch logic to another file and then just import it inside nuxt.config ? ( with this nuxt.config gets a lot cleaner )
I have posted a discussion on this to be used with Nuxt's new routeRules, but I am struggling to still work out the best way. I have done something inspired by your solution @MartCube but not sure if what I have done will affect performance in a bad way or not. Can you spot any issues with this? https://github.com/nuxt/framework/discussions/9673