Create a Simple Node Cache With Express Node JS

This article provides a sample application using the Node Cache with explanation.

Please see this article on how to create an Express Node JS application, so that we can quickly jump into the topic without further delay.

Why is caching required?

When the same response needs to be served multiple times, store the data in app memory cache and it can be retrieved faster than the data retrieved from the storage layer for every single call. Caching is an ability of an application to duplicate the values for a specified period of time and serve the web request instantly.

These techniques will be effective when

  • There is a need to call for a 3rd party API and the call counts
  • Cost of data transfer between cloud and the server.
  • Server response is critical based on the concurrent requests.

What is Node Cache?

When the data is retrieved from the database before serving to the request browser, the data will be stored in the application process memory. On further requests the data will be served from the app memory cache rather than from database.

Advantages of Node Cache

  • Network call is not required.
  • Performance of the application can be improvised with very less efforts.
  • Minimal requirement for the implementation.

Create an Express Node JS application

Open the PowerShell or cmd prompt window and go to the destined folder.

Execute the following command

npx express expressNodeCaching --hbs

Install the modules using the command

npm i

and install the following additional packages

npm i node-cache

npm i isomorphic-fetch

Once all the packages are installed and ready to start, I have created a new route page called “getCached.js” and mapping the “App.js” page.

app.use('/getCached', require('./routes/getCached'));

Upon calling the endpoint the logic is to fetch the response from JSON placeholder (mock API) site, store the data in Node Cache and respond to the request. Upon further request, cached data will be served.

const express = require('express');
const nodecache = require('node-cache');
require('isomorphic-fetch');

const appCache = new nodecache({ stdTTL : 3599});
const router = express.Router();
const todosURL = 'https://jsonplaceholder.typicode.com/todos';

router.get('/', async (req,res) => {
    if(appCache.has('todos')){
        console.log('Get data from Node Cache');
        return res.send(appCache.get('todos'))
    }
    else{
        const data = await fetch(todosURL)
            .then((response) => response.json());
        appCache.set("todos",data);
        console.log('Fetch data from API');
        res.send(data);         
    }
})

router.get('/stats',(req,res)=>{
    res.send(appCache.getStats());
})

module.exports = router

Object created using the node-cache is

new nodecache({ stdTTL : 3599});

With options

stdTTL : standard time to live in seconds where default is 0 and 0 is unlimited.

Checkperiod : to check interval in seconds for fetching new data and delete automatically the older value. Default is 600 where 0 is no periodic check.

useClones : to enable or disable the cloning of variables. Default is true, then you will get a cached copy of variable.

deleteOnExpire : to delete the variable automatically on expiry. Default is true.

enableLegacyCallbacks : to re-enable the usage of callbacks instead of sync functions. Default is false.

maxKeys : to specify a maximum amount of keys that can be stored in the cache. Default is -1 where -1 disables the key limit.

Now it’s time to run the app by executing the command

npm start

Create a simple Node Cache with Express Node JS

On the first hit, the data is fetched from the source API with the response time of approximately 969ms and the same has been stored in the app memory Node Cache. The second hit gets the data from the cached with the remarkable reduction in fetch time of just ~13 ms.

Thus, the objective is met with a few very easy steps.