Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 944
megloff Avatar asked Feb 03 '20 20:02

megloff


Video Answer


1 Answers

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

like image 104
Eduard Avatar answered Oct 01 '22 18:10

Eduard