Nuxt and Sanity work great together to provide a great experience both for developers and the content editors. But one thing I’ve noticed when visiting others’ sites or even my own (I thought everything I made was perfect?), is the loading times in between pages. You click a link, nothing happens for a few seconds, and then finally the page changes.
That’s not a very great experience, and it makes you wonder what the point of going headless even is, if the cache is “dumb” and doesn’t always have data ready to serve. Even WordPress-sites know better than that!
One solution could be to continuously crawl through the site to ensure the pages are always “hot” and cached, but on larger sites, this seems like a vastly inefficient solution, and it would regardless be wasting compute by constantly having to go through the site, regardless of the number of visitors. But since we’re working with such a flexible CMS, wouldn’t it be possible to just have the cache be eternal? And just trigger a cache reload when content has changed?
This can actually be done by adding webhooks to Sanity and setting them to trigger on “Create”, “Update”, and “Delete”. Then, using Nuxt server routes, creating a small route that clears the cache.
// server/api/cache.get.js
export default defineEventHandler(async() => {
const storage = useStorage('cache')
const keys = await storage.getKeys('nitro:routes')
await Promise.all(keys.map(key => storage.removeItem(key)))
return {
success: true
}
})

