Cache Axios

Axios is a Promise based HTTP client:

I would like to implement a cache control for GET requests. So that I don't query the same URL twice during a page load. That would be a cache that works for 10-20 seconds.

I would like to implement it as transparent as possible. Right now I call Axios by window.axios.get(url).then(response => {}) and the best would be to override the .get() method to inject the cache system.

Comments (5)

Marco Alka's photo

I wrote a cache system once, which works like this:

  1. Start by calculating a hash from all arguments which are important for the request, so that you only cache same requests and not slightly differing ones, which would lead to problems.
  2. Check your cache (a simple Map should work) if it contains the result data and when the call was made (timestamp)
  3. If not, check a second Map, which buffers in-transit request Promises
  4. If there is no entry, make the actual call. In any case, create a Promise and store an array with the next item containing refs to the Promise's resolve and reject methods.
  5. Once the call finishes, resolve (or reject) all Promises by calling the correct method from the buffer Map.
  6. Last but not least, store the result in the cache Map together with a timestamp.

Hashing the parameters should be simple, if you JSON-stringify them and then use something like this for the hash:

const hash = str => str.split('').reduce((prevHash, currVal) =>
    (((prevHash << 5) - prevHash) + currVal.charCodeAt(0))|0, 0);
Show +2 replies
Emil Moe's photo

Software Engineer & Consultant

Thanks. I got something to work now. Not sure if it is as pretty as yours, but it seems to work without having to make changes to existing code.

let calcHash = function(s) {
    for(var i = 0, h = 0xdeadbeef; i < s.length; i++)
        h = Math.imul(h ^ s.charCodeAt(i), 2654435761)
    return (h ^ h >>> 16) >>> 0

let cache = new Map()
let buffer = new Map()

window.axios.get = (url, config) => {
    let hash = calcHash(url + JSON.stringify(config))

    if (cache.has(hash)) {
        return new Promise((resolve, reject) => {

    if (buffer.has(hash)) {
        return buffer.get(hash)

        window.axios.request(Object.assign(config || {}, {
            method: 'GET',
            url: url

    buffer.get(hash).then(response => {
        cache.set(hash, response)

    return buffer.get(hash)
Emil Moe's photo

Software Engineer & Consultant

Of course this introduces the possibility of errors if wanting to load the same list twice (after modifications).

Either I will delete the cache after a few seconds or there should be a option to force load.

Of course config can be used to include a unique ID