skip to Main Content

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:

  1. Make API request once at build-time
  2. Access or Commit this data to Vuex
  3. Not have to request this at each SSR
  4. 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


  1. Chosen as BEST ANSWER

    Here's what I'm using so far:

    build module

    import fs from "fs";
    const getCachedApiRequests: Module<Options> = async function () {
       const data = await getData();
       fs.writeFileSync("./data.json", JSON.stringify(data), "utf8");
    }
    
    
    const config: NuxtConfig = {
        buildModules: [
           async () => {
               await getCachedApiRequests();
           }
        ]
    }
    

    nuxtServerInit.ts

    import data from "./data.json";
    
    export async function nuxtServerInit({ dispatch, commit }, context) {
        commit('setData', data);
    }
    

  2. 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:

    export default {
      target: 'static' // default is 'server'
    }
    

    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 many NuxtLinks 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search