megloff
megloff

Reputation: 1566

nuxt.js - How to cache axios call at server side for all clients

I am using a vue + nuxt.js application, I like to know if it is possible to cache an axios webservice call for all clients. I have to get some currency reference data and this makes not much sense that every client has to call this data.

Can someone provide me some hints or even an example? Thx.

Upvotes: 5

Views: 9451

Answers (2)

zia
zia

Reputation: 278

here is the new solution for cache the whole page

even you can cache consistent api like menu if you need

https://www.npmjs.com/package/nuxt-perfect-cache

npm i nuxt-perfect-cache

// nuxt.config.js

modules: [
    [
        'nuxt-perfect-cache',
        {
          disable: false,
          appendHost: true,
          ignoreConnectionErrors:false, //it's better to be true in production
          prefix: 'r-',
          url: 'redis://127.0.0.1:6379',
          getCacheData(route, context) {          
            if (route !== '/') {
              return false
            }
            return { key: 'my-home-page', expire: 60 * 60 }//1hour
          }
        }
      ]
]

then for cache your api response in redis for all clients:

asyncData(ctx) {
    return ctx.$cacheFetch({ key: 'myApiKey', expire: 60 * 2 }, () => {
      console.log('my callback called*******')
      return ctx.$axios.$get('https://jsonplaceholder.typicode.com/todos/1')
    })
  }

Upvotes: 2

Eduard
Eduard

Reputation: 133

Here is working solution with latest Nuxt 2.11, using locally defined module.

First add a local module to nuxt.config.js

modules: [
   "@/modules/axCache",
...
]

Then

//  modules/axCache.js
import LRU from "lru-cache"

export default function(_moduleOptions) {
  const ONE_HOUR = 1000 * 60 * 60
  const axCache = new LRU({ maxAge: ONE_HOUR })

  this.nuxt.hook("vue-renderer:ssr:prepareContext", ssrContext => {
    ssrContext.$axCache = axCache
  })
}

and

// plugins/axios.js
import { cacheAdapterEnhancer } from "axios-extensions"
import LRU from "lru-cache"
const ONE_HOUR = 1000 * 60 * 60

export default function({ $axios, ssrContext }) {
  const defaultCache = process.server
    ? ssrContext.$axCache
    : new LRU({ maxAge: ONE_HOUR })

  const defaults = $axios.defaults
  // https://github.com/kuitos/axios-extensions
  defaults.adapter = cacheAdapterEnhancer(defaults.adapter, {
    enabledByDefault: false,
    cacheFlag: "useCache",
    defaultCache
  })
}

Note, this works for both server/client sides and can be configured to work only on one side.

solution found on: https://github.com/nuxt-community/axios-module/issues/99

Upvotes: 8

Related Questions