Is it possible to make an API request at build-time, and cache that so it’s available in-memory for all future SSR requests?
My use case is that I have data needed to render server-side (for SEO reasons), but it’s stored in a database.
I don’t want to make this API request for every SSR request.
Ideally:
- Make API request once at build-time
- Access or Commit this data to Vuex
- Not have to request this at each SSR
- Refresh the data once every 24 hours
I’ve looked into a few SO answers, and all seem to point to Redis-based cache. Is there no way to do this in-memory.
For example, I use nuxtServerInit
:
async nuxtServerInit({ dispatch, commit }, context: Context) {
// check if already in memory?
if (somehowInMemory) {
commit(cache)
} else {
const serverDataJson = await dispatch("getServerData");
// store this json in memory?
cache = serverDataJson;
commit(cache);
}
}
2
Answers
Here's what I'm using so far:
build module
nuxtServerInit.ts
Nuxt2 provides Static Site Generation. Nuxt3 right now has this future experimental.
All you need to do is to set your nuxt.config.ts file a variable:
To generate all pages you want. You need to make one page/component where you make a request to get all links you need to generate. Create "for" loop in template for them with
<NuxtLink>
tag. Nuxt in build time will know it has a manyNuxtLinks
to generate as static sites.Application will keep SPA as soon it hit client browser, so you still need to have database open. To exclude pages from generation, you have
generate.exclude
property.You can find more information about this in Nuxt2 documentation
Files will be saved on server Hard Drive, not a RAM memory. I’m pretty sure you just want to avoid unnecessary API calls to your database, so this detail should not be an issue.
Nuxt team not provide any tools to repeat this process every 24h. But I’m pretty sure you can find any solution to this instead of by your self generate static sites every day.