← Impulso Blog

Caching JavaScript requests with axios

Learn how to avoid making too many requests by caching JavaScript requests with axios.

Two people working on laptops at an office desk.

Editorial translation by Impulso.

Greater control over the cache and configurable storage for REST request results are essential requirements, especially in modern applications that aim to avoid making too many requests.

Without caching, every request reaches the server. With caching, the first reaches the server and later requests can use the stored result.

Setting up axios in code

As the name suggests, axios-cache-adapter is an adapter that helps manage the request cache. It lets you set maxAge, the maximum time before the data expires, directly in axios.

1 import { setupCache } from 'axios-cache-adapter'
2 import axios from 'axios-cache-adapter'
3
4 const cache = setupCache({
5   maxAge: 15 * 60 * 1000 // 15 minutos para expiração
6 })
7
8 const api = axios.create({
9   adapter: cache.adapter
10 })

In the previous code snippet, we import the setupCache function on line 1. On line 4, we pass it an object with the maxAge property to define when the data in the adapter expires. In the example above, the data expires after 15 minutes. On line 8, we can configure the adapter directly in axios so that identical requests within the 15-minute window are served by the adapter instead of being sent to the server.

Setup

With that in mind, we can make a significant improvement by using the setup function to get a preconfigured axios instance from axios-cache-adapter. This lets you remove axios as a direct dependency from your project:

1 import { setup } from 'axios-cache-adapter'
2
3 const api = setup({
4  baseURL: 'http://some-rest.api',
5  cache: {
6    maxAge: 15 * 60 * 1000  }
7 })

In the previous code snippet, we import the setup function on line 1 and create an axios instance by preconfiguring axios-cache-adapter with a 15-minute cache lifetime.

This might bring a few questions to mind:

  • Is there a way to set the cache expiration time for a specific request?
  • How can I make sure the request goes to the server even if the data in the cache hasn’t expired?

The global configuration makes it easier to set when data expires, but you can override the cache settings for specific requests:

api.get('/get?with=query', {
  cache: {
    maxAge: 2 * 60 * 1000
  }
})

To make sure the request returns fresh data, you can use the cache-control parameter. Setting this parameter to no-cache ensures that the requested data comes from the server, as shown in the following code:

api.get('/get?with=query&cache-control=no-cache')

Storage location

By default, the data is stored in memory. That means refreshing the page clears the cache. If that’s not the behavior you want, localforage offers a solution.

With it, you can provide axios-cache-adapter with an instance that stores the data in place of the default in-memory storage. It’s worth noting that this approach only works on the client side because localforage doesn’t work in Node.js

import localforage from 'localforage'
import memoryDriver from 'localforage-memoryStorageDriver'
import { setup } from 'axios-cache-adapter'

// Configura `localforage` e retorna uma instância do `axios` com `axios-cache-adapter`
async function configure () {
  // Registre o `memoryDriver` customizado para` localforage`
  await localforage.defineDriver(memoryDriver)

// Cria uma instância do `localforage`
  const store = localforage.createInstance({
    // Lista os drivers usados
    driver: [
      localforage.INDEXEDDB,
      localforage.LOCALSTORAGE,
      memoryDriver._driver
    ],
    // Adiciona prefixo em todas as chaves de armazenamento para evitar conflitos
    name: 'my-cache'
  })

return setup({
    baseURL: 'http://some-rest.api',
    cache: {
      maxAge: 15 * 60 * 1000,
      store // Adicionar a instância do `localforage` no armazenamento do `axios-cache-adapter`
    }
  })
}

configure().then(async (api) => {
  const response = await api.get('/url')

What this means

With all these configuration options, you can control the request cache and cut down on unnecessary requests. That makes your life a lot easier. Of course, this is just one way to handle multiple requests on the server. If you’re looking for more tips like these, follow our blog for more posts like this one.

Related articles